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

html, php, preg-replace, regex

Solution

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

Problem

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?!

Original source