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?!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With