PHP:用preg_replace替换错误的HTML


PHP: Wrong HTML replacement with preg_replace.

我正在制作用PHP替换特定img标记的函数。但是到目前为止做得不好。

代码低于

define('IMG_REG', '/<img.*?>/i');
$str = '<p>aaa</p><img src="aaa" >
<p>iii</p><img src="aaa" >
<p>uuu</p><img src="aaa" >
<p>eee</p><img src="aaa" >
<p>ooo</p><img src="aaa" >' ;
$num = 3;
if ( preg_match_all(IMG_REG, $str, $m, PREG_OFFSET_CAPTURE) > $num-1 ) {
    $target = $m[0][$num-1][0];
    $new = $target.'!!!';
    if( $target != NULL ):
        $str = preg_replace( $target, $new, $str, $num);
    endif;
}
echo $str;

我想将前3个"img标记"更改为"img标记"+"!!"。

所以。。。理想的结果就像这个

<p>aaa</p><img src="aaa" >!!!
<p>iii</p><img src="aaa" >!!!
<p>uuu</p><img src="aaa" >!!!
<p>eee</p><img src="aaa" >
<p>ooo</p><img src="aaa" >

但是。。。实际结果就像

<p>aaa</p><<img src="aaa" >!!!>
<p>iii</p><<img src="aaa" >!!!>
<p>uuu</p><<img src="aaa" >!!!>
<p>eee</p><img src="aaa" >
<p>ooo</p><img src="aaa" >

有一些'<lt;'&'!!>'。我不知道为什么。。。

做我的主人!谢谢

您忘记在"$target"regex上添加分隔符。

试试这个:

define('IMG_REG', '#<img (.*)>#');
$str = '<p>aaa</p><img src="aaa" >
<p>iii</p><img src="aaa" >
<p>uuu</p><img src="aaa" >
<p>eee</p><img src="aaa" >
<p>ooo</p><img src="aaa" >' ;
$num = 3;
if ( preg_match_all(IMG_REG, $str, $m, PREG_OFFSET_CAPTURE) > $num-1 )    
{
    $target = $m[0][$num-1][0];
    $new = $target.'!!!';
    $target = "/".$target."/"; //Delimiters here!!!
    if( $target != NULL ):
       $str = preg_replace( $target, $new, $str, $num);
    endif;
}
echo $str;
$str = preg_replace('/<img (.*)>/', "<img $1>!!!", $str, $num);

在这里,换到上面的线。