Search code examples
phpregexregexp-replace

How to write a regular expression in PHP


Using a 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?


Solution

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

    Edit:

    Forgot this is Linux, \r must be optional.