如何在 php preg_replace 中剥离 ${1}?

How to strip ${1} in php preg_replace?

我正在尝试替换脚本和 img 标签的来源 (src)。我有 '../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="" src="' . $help_path . ' "></script>',
    '<img src="' . $help_path . '" alt="" style="" />'
);

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

?>

这是我正在处理的 link 图像:

<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>

您可以 "trim" 通过 从相应的捕获组中排除 您进入反向引用的内容:

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

将匹配并且 不捕获 ../ 并将捕获其余部分到组中。

这是代码修复:

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

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

查看 PHP demo:

$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="" src="' . $help_path . '"></script>',
    '<img src="' . $help_path . '" alt="" />'
);

$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>