Как раздеть $ {1} в php preg_replace? - PullRequest
2 голосов
/ 09 апреля 2019

Я пытаюсь заменить исходники (src) для сценария и тегов img.У меня есть «../filename.js», и я хочу избавиться от 2 точек, как мне это сделать?

<?php

$file_path = content_url() . '/help/WS/WAS_B.htm';

$contents = wp_remote_fopen( $file_path );

$help_path = content_url() . '/help/';

$find = array(
    '#<script type="(.*?)" src="(.*?)">(.*?)</script>#is',
    '/<img src="(.*)" alt="(.*)" style="(.*)" \/>/i'
);

$replace = array(
    '<script type="${1}" src="' . $help_path . ' ${2}"></script>',
    '<img src="' . $help_path . '${1}" alt="${2}" style="${3}" />'
);

$preg_rep = preg_replace($find, $replace, $contents);

?>

Это ссылка и изображение, над которым я работаю:

<img src="../Links/WAS_PIC_ControlBox-1-2-3.jpg" alt="WAS-Betjeningsboks-1-2-3" 
style="border: none; margin-left: 20px; margin-right: 0px; margin-top: 0px; margin-bottom: 0px;" border="0">

<script type="text/javascript" src="../ehlpdhtm.js"></script>

Вывод, который я хотел бы получить, должен быть таким:

<img src="http:xxx.com/wp-content/help/Links/WAS_PIC_ControlBox-1-2-3.jpg" alt="WAS-Betjeningsboks-1-2-3" 
style="border: none; margin-left: 20px; margin-right: 0px; margin-top: 0px; margin-bottom: 0px;" border="0">

<script type="text/javascript" src="http:xxx.com/wp-content/help/ehlpdhtm.js"></script>

1 Ответ

1 голос
/ 09 апреля 2019

Вы можете «обрезать» то, что получаете в обратной ссылке, на , исключая эту часть из соответствующей группы захвата:

(?:\.\./)?(.*?)

будет совпадать, а не захватывать ../ и захватит остальных в группу.

Вот код исправления:

$find = array(
    '#<script\s+type="(.*?)"\s+src="(?:\.{2}/)?(.*?)">(.*?)</script>#is',
    '#<img\s+src="(?:\.{2}/)?(.*?)"\s+alt="(.*?)"([^>]*?)/?>#i'
);

$replace = array(
    '<script type="${1}" src="' . $help_path . '${2}"></script>',
    '<img src="' . $help_path . '${1}" alt="${2}"${3} />'
);

См. PHP демо :

$help_path = 'http:xxx.com/wp-content/help/';
$contents = <<<MYVAR
<img src="../Links/WAS_PIC_ControlBox-1-2-3.jpg" alt="WAS-Betjeningsboks-1-2-3" 
style="border: none; margin-left: 20px; margin-right: 0px; margin-top: 0px; margin-bottom: 0px;" border="0">

<script type="text/javascript" src="../ehlpdhtm.js"></script>
MYVAR;

$find = array(
    '#<script\s+type="(.*?)"\s+src="(?:\.{2}/)?(.*?)">(.*?)</script>#is',
    '#<img\s+src="(?:\.{2}/)?(.*?)"\s+alt="(.*?)"([^>]*?)/?>#i'
);

$replace = array(
    '<script type="${1}" src="' . $help_path . '${2}"></script>',
    '<img src="' . $help_path . '${1}" alt="${2}"${3} />'
);

$preg_rep = preg_replace($find, $replace, $contents);
print_r($preg_rep);

Выход:

<img src="http:xxx.com/wp-content/help/Links/WAS_PIC_ControlBox-1-2-3.jpg" alt="WAS-Betjeningsboks-1-2-3" 
style="border: none; margin-left: 20px; margin-right: 0px; margin-top: 0px; margin-bottom: 0px;" border="0" />

<script type="text/javascript" src="http:xxx.com/wp-content/help/ehlpdhtm.js"></script>
...