【问题标题】:php regex to identify all HTML special chars in decoded stringphp正则表达式识别解码字符串中的所有HTML特殊字符
【发布时间】:2012-12-03 19:20:51
【问题描述】:

我希望已经在 SO 中找到它......但到目前为止还没有

我说的是一个查看 HTML ENCODED 字符串的正则表达式:例如像

blip ♦ trout’s mouth

我是否用&\w+;&#[0-9]+; 覆盖了所有基础?

$encoded_string = htmlspecialchars($_GET["searchterms"]);
echo "<b>Search results for submitted string: \"$encoded_string\"</b><br><br>";
$html_special_chars_pattern = "!(&\\w+;|&#[0-9]+;)!";
$non_html_tokens = preg_split( $html_special_chars_pattern, $encoded_string, -1, PREG_SPLIT_DELIM_CAPTURE );

【问题讨论】:

    标签: php html regex decoding


    【解决方案1】:

    我已将my earlier related post 作为答案。如果其他人提出了更好的解决方案或为什么会失败,请告诉我:)

    preg_match_all('/&(?:[a-z]+|#\d+);/', $content, $matches);
    

    也支持十六进制实体:

    preg_match_all('/&(?:[a-z]+|#x?\d+);/i', $content, $matches);
    

    顺便说一句,(?: ... ) 用于防止内存捕获。另见:What does `?` mean in this Perl regex?

    【讨论】:

    • 谢谢...正如您在下面的答案中看到的那样,似乎还有十六进制参考的问题。另外我想了解“?:”序列在您的正则表达式中具有什么功能...
    • @mikerodent, (?:) 是非捕获组
    【解决方案2】:

    您缺少&amp;#xH; or &amp;#XH; numeric character references

    5.3.1 数字字符引用

    数字字符引用指定字符在文档字符集中的代码位置。数字字符引用可能有两种形式:

    • 语法“D;”,其中 D 是十进制数,指的是 ISO 10646 十进制字符数 D。

    • 语法“H;”或“H;”,其中 H 是十六进制数,指的是 ISO 10646 十六进制字符数 H。数字字符引用中的十六进制数不区分大小写。

    即正则表达式中的&amp;#[xX][a-fA-F0-9]+;

    【讨论】:

    • 谢谢...就您所知,这是否涵盖了所有 HTML 实体(引用等)?
    • @mikerodent,据我所知,是的
    • @Alexander +1 感谢您的参考:)
    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多