str_replace html 内容无效

str_replace on an html content not working

我有这个HTML内容:

$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>';

我有 str_replace 的代码,因此它会为 img:

添加结束标记
$new = str_replace('"></div>', '"/></div>', $test);

echo $new;

当使用 inspect element 检查时,图像没有按预期关闭。我在这里做错了什么?

补充说明:

我需要结束标记才能使 PHPWord 正常工作。此外,$test 的值来自 $_POST,因为这是通过 AJAX.

馈送的

谢谢

标签和结束标签之间有一个换行符。您应该重新格式化 $test 变量或使用:

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

然而,您处于危险区域,因为所有火柴都将被替换。 HTML 是一种语言 not play well with regex.

如果可能的话,最好在问题变成 html 形式之前解决问题。

要执行您要查找的操作,您需要搜索该行中的文本(其他答案也更直接地说明 - 问题是换行符。

$new = str_replace('ck;">\n</div><section>','ck;">\n</div></div><section>',$test);