PHP替换少于HTML字符串内部

时间:2016-03-10 18:53:07

标签: php html regex

假设您有一个字符串<div>some text with symbol < inside </div>,如何在不触及小于div标签的情况下将<替换为&lt;

这只是一个例子,字符串可能更大,并且出现了多个<

预期结果:<div>some text with symbol &lt; inside </div>

3 个答案:

答案 0 :(得分:2)

在你再继续之前:

引自RegEx match open tags except XHTML self-contained tags

  

您无法使用正则表达式解析[X] HTML。因为正则表达式无法解析HTML。正则表达式不是可用于正确解析HTML的工具。 [...]正则表达式是一种不太复杂的工具,无法理解HTML所使用的构造。 HTML不是常规语言,因此无法通过正则表达式进行解析。正则表达式查询无法将HTML分解为有意义的部分。

以下是解决问题的分步解决方案:

  1. 使用XML解析器。如果您只有完整的HTML;
  2. 在内容上使用htmlspecialchars()htmlentities()
  3. 我不会解释如何执行此操作,因为Google上已有大量有关此主题的文章。

    并且,请停止使用正则表达式来处理HTML!

答案 1 :(得分:1)

这应该有效:

$html = preg_replace('/(?!<[a-zA-Z=\"\':; ]*[^ ]>|<\\/[a-zA-Z="\':; ]*>)(<)/', "&lt;", $html);

编辑:  虽然我建议做@Ismael Miguel建议的事情,如果你想纯粹用正则表达式做这件事,我已经修改了上面的工作。

答案 2 :(得分:0)

当您确定知道div中没有​​其他标签时,您可以使用此代码段:

$html = '<div class="toto">some <div>text</div> with symbol < inside. Possible to have math expression < and > . </div><div> 4 < 5 > 2</div>';

$html = preg_replace_callback( '#(<div[^>]*>)(.*)(<\/div>)#Ui',
        function ($matches) { return $matches[1] . htmlentities($matches[2]) . $matches[3]; },
        $html);

echo $html;

// <div class="toto">some &lt;div&gt;text</div> with symbol < inside. Possible to have math expression < and > . </div><div> 4 &lt; 5 &gt; 2</div>