如何用 '../' 匹配和替换 img 源

How to match and replace img source with '../'

我想删除图像源 (src) 中任意数量的“../”。

我有正则表达式,它会删除“../”,如果源中没有“../”也可以使用。

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

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

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

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

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

问题是,如果 src 中有多个“../”,我的正则表达式会输出“../”。它应该总是像 src="Links/xxx.jpg",不管源代码中有多少 '../' ('../../../../').

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

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

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

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

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

您可以使用preg_replace删除所有../

$contents = str_replace('../', '', $contents);

之后,您可以应用正则表达式

$contents = str_replace('../', '', $contents);
$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);