简体   繁体   中英

Please help me write a regular expression on PHP

Please help me write a correct regular expression. I need to find and replace only those elements that occur in a row from 2 to 10 times in the content of the text and replace them with something else.

Text example:

$text = '<p>Text text text</p>
<p><a href="#" class="img" target="_blank"><img src="pic_1.jpg" alt=""></a></p>
<p>Text text text</p>
<p><a href="#" class="img" target="_blank"><img src="pic_2.jpg" alt=""></a></p>
<p><a href="#" class="img" target="_blank"><img src="pic_3.jpg" alt=""></a></p>
<p><a href="#" class="img" target="_blank"><img src="pic_4.jpg" alt=""></a></p>
<p><a href="#" class="img" target="_blank"><img src="pic_5.jpg" alt=""></a></p>
<p>Text text text</p>
<p>Text text text</p>
<p>Text text text</p>
<p><a href="#" class="img" target="_blank"><img src="pic_6.jpg" alt=""></a></p>
<p>Text text text</p>';

My regular example:

$regular = "#(<p><a href=['\"](.+?)['\"] class=['\"]img['\"]([^>]+)><img([^>]+)></a></p>){2,10}#is";

I'll try like this

echo preg_replace_callback($regular, function ($matches) {
    return 'some replace text example';
}, $text);

I expect to receive:

<p>Text text text</p>
<p><a href="#" class="img" target="_blank"><img src="pic_1.jpg" alt=""></a></p>
<p>Text text text</p>
some replace text example
some replace text example
some replace text example
some replace text example
<p>Text text text</p>
<p>Text text text</p>
<p>Text text text</p>
<p><a href="#" class="img" target="_blank"><img src="pic_6.jpg" alt=""></a></p>
<p>Text text text</p>

but it doesn't work. What did I do it wrong?

You can use this regex:

$regular = "#(<p><a href=['\"](.+?)['\"] class=['\"]img['\"]([^>]+)><img([^>]+)></a></p>\r\n){2,10}#i";

Note I have added \r\n and removed the s flag.

The lines are always separated by \r\n so that must be part of the match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM