正则表达式替换PHP中的html src属性

时间:2012-05-18 19:02:10

标签: php html regex

我正在尝试使用正则表达式替换PHP中的源属性(可能是图像或任何标记)。

我有一个这样的字符串:

$string2 = "<html><body><img src = 'images/test.jpg' /><img src = 'http://test.com/images/test3.jpg'/><video controls="controls" src='../videos/movie.ogg'></video></body></html>";

我想把它变成:

$string2 = "<html><body><img src = 'test.jpg' /><img src = 'test3.jpg'/><video controls="controls" src='movie.ogg'></video></body></html>";

继承我尝试的内容:

$string2 = preg_replace("/src=["']([/])(.*)?["'] /", "'src=' . convert_url('$1') . ')'" , $string2);
echo htmlentities ($string2);

基本上它没有改变任何东西,并且给了我关于未转义字符串的警告。

$1不发送字符串的内容吗?这有什么不对?

convert_url的功能来自我之前发布的一个例子:

function convert_url($url)
{
    if (preg_match('#^https?://#', $url)) {
        $url = parse_url($url, PHP_URL_PATH);
    }
    return basename($url);
}

它应该删除url路径并返回文件名。

3 个答案:

答案 0 :(得分:13)

不要在HTML上使用正则表达式 - 使用DOMDocument类。

$html = "<html>
           <body>
             <img src='images/test.jpg' />
             <img src='http://test.com/images/test3.jpg'/>
             <video controls='controls' src='../videos/movie.ogg'></video>
           </body>
         </html>";

$dom = new DOMDocument;  
libxml_use_internal_errors(true);

$dom->loadHTML( $html ); 
$xpath = new DOMXPath( $dom );
libxml_clear_errors();

$doc = $dom->getElementsByTagName("html")->item(0);
$src = $xpath->query(".//@src");

foreach ( $src as $s ) {
  $s->nodeValue = array_pop( explode( "/", $s->nodeValue ) );
}

$output = $dom->saveXML( $doc );

echo $output;

其中输出以下内容:

<html>
  <body>
    <img src="test.jpg">
    <img src="test3.jpg">
    <video controls="controls" src="movie.ogg"></video>
  </body>
</html>

答案 1 :(得分:1)

您必须使用e修饰符。

$string = "<html><body><img src='images/test.jpg' /><img src='http://test.com/images/test3.jpg'/><video controls=\"controls\" src='../videos/movie.ogg'></video></body></html>";

$string2 = preg_replace("~src=[']([^']+)[']~e", '"src=\'" . convert_url("$1") . "\'"', $string);

请注意,使用e修饰符时,替换脚本片段必须是字符串,以防止在调用preg_replace之前解释它。

答案 2 :(得分:1)

function replace_img_src($img_tag) {
    $doc = new DOMDocument();
    $doc->loadHTML($img_tag);
    $tags = $doc->getElementsByTagName('img');
    foreach ($tags as $tag) {
        $old_src = $tag->getAttribute('src');
        $new_src_url = 'website.com/assets/'.$old_src;
        $tag->setAttribute('src', $new_src_url);
    }
    return $doc->saveHTML();
}