Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a whole div with an other with preg_replace regEx

i don't get it how to replace a div with an other in PHP preg_replace

$string ='
  <div id="myid">this has to be replaced</div>
  <p>here is something</p>
  <div id="any">any text not to be replaced</div>
';

if i do

$string = preg_replace('/<div id=\"myid\">.*<\/div>/','anything',$string);

it does not work and i don't get why?!

like image 989
Viktor Avatar asked Dec 07 '25 19:12

Viktor


1 Answers

Since your regex is working fine I suspect that you didn't assign the return value of preg_replace to any variables.

$string = preg_replace('/<div id=\"myid\">.*<\/div>/','anything',$string);

should work.


After you edited your question:

As @Felix Kling mentioned, .* is greedy, that means it matches everything until the last match. You can use the non-greedy quantifier (ie. .*?). The following should work:

$string = preg_replace('/<div id=\"myid\">.*?<\/div>/','anything',$string);
like image 160
fardjad Avatar answered Dec 09 '25 09:12

fardjad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!