在php中用文本替换小于**(<)**和大于**(>)**的符号

时间:2016-02-05 10:08:43

标签: php

我搜索了一段时间的脚本,可以看到html标签和&lt;之间的区别。和&gt;放在文字中, 原因是我从数据库接收文本, 哪个是由html表单插入的,包含text和html标签, 文本可以包含&lt;和&gt;,标签也一样, 使用htmlspecialchars,您可以将文本验证为XHTML, 但您也会将标记更改为<b>&lt;b&gt;, 所以我需要一个可以看出这两者之间差异的脚本......

请解决我的问题。

1 个答案:

答案 0 :(得分:0)

如果我们可以假设......

  • html标记中的&lt; &gt; 字符未包含,带有空格
  • 相同的字符在条件中被空格包围
  • 在条件下,这些组合存在&lt; &gt; &lt; = &gt; = !&lt; !&gt;

......这可能是一个解决方案:

$result = preg_replace('/ ([!]{0,1})(<)([=]{0,1}) /', '$1&lt;$3', $string);
$result = preg_replace('/ ([!]{0,1})(>)([=]{0,1}) /', '$1&lt;$3', $result);

这是正则表达式对&lt; 字符的含义:

\         # Match the character “ ” literally
(         # Match the regular expression below and capture its match into backreference number 1
   [!]       # Match the character “!”
      {0,1}      # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
(         # Match the regular expression below and capture its match into backreference number 2
   <         # Match the character “<” literally
)
(         # Match the regular expression below and capture its match into backreference number 3
   [=]       # Match the character “=”
      {0,1}      # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
\         # Match the character “ ” literally