PHP:使用preg_replace替换错误的HTML。

I'm making function to replace specific img tag with PHP. But... not doing well so far.

code is below

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;

I want to change first 3 "img tag" to "img tag" + "!!!".

So... ideal result is like this

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

But... actual result is like

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

There are some '<<' & '!!!>'. I can't tell why...

Be my Master! Thanks.

You forgot to add the delimiters on the "$target" regex.

Try this:

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

here it is, change to above line.