Search code examples
phphtmlphpword

str_replace on an html content not working


I have this HTML content:

$test = '<section><div class="row">
        <div class="col-xs-12" data-type="container-content">
        <section data-type="component-photo"><div class="photo-panel">
        <img src="http://somewhere.com/XpV8lCLD6pChrysanthemum.jpg" width="100%" height="" style="display: inline-block;">
</div></section></div>
</div></section>';

And I have this code for str_replace so that it will add a closing tag for the img:

$new = str_replace('"></div>', '"/></div>', $test);

echo $new;

When check this out using inspect element the image is not closed as expected. What could I be doing wrong here?

Additional notes:

I need the closing tag for PHPWord to work. Also, The value of $test is from $_POST as this is fed through AJAX.

Thank you


Solution

  • There is a newline between the tag and the closing tag. You should either reformat the $test variable or use:

    $new = preg_replace('/>[\n\r]<\/div>/', '/></div>', $test);
    

    You are however in dangerous territory here as all matches will be replaced. HTML is a language that does not play well with regex.

    It's much better to tackle the problem before it takes html form if possible.