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

372

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

141

Answer

Solution:

Since yourregex is working fine I suspect that you didn't assign the return value ofpreg_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);

People are also looking for solutions to the problem: php - jquery tree view checkbox passing values

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.