【问题标题】:PHP html_entity_decode and trim confusionPHP html_entity_decode 和修剪混淆
【发布时间】:2016-02-03 13:46:57
【问题描述】:

我正在尝试使用strip_tagstrim 来检测字符串是否包含空html?

$description = '<p>&nbsp;</p>';

$output = trim(strip_tags(html_entity_decode($description, ENT_QUOTES, 'UTF-8')));

var_dump($output);

字符串'Â'(长度=2)

我的调试尝试解决这个问题:

$description = '<p>&nbsp;</p>';

$test = mb_detect_encoding($description);
$test .= "\n";
$test .= trim(strip_tags(html_entity_decode($description, ENT_QUOTES, 'UTF-8')));
$test .= "\n";
$test .= html_entity_decode($description, ENT_QUOTES, 'UTF-8');

file_put_contents('debug.txt', $test);

输出:debug.txt

ASCII
 
<p> </p>

【问题讨论】:

    标签: php


    【解决方案1】:

    如果您使用var_dump(urlencode($output)),您会看到它输出string(6) "%C2%A0",因此字符码是0xC2 和0xA0。 These two charcodes are unicode for "non-breaking-space"。确保您的文件以 UTF-8 格式保存,并且您的 HTTP 标头为 UTF-8 格式。

    也就是说,要修剪这个字符,您可以使用带有 unicode 修饰符的正则表达式(而不是修剪):

    DEMO:

    <?php
    
    $description = '<p>&nbsp;</p>';
    
    $output = trim(strip_tags(html_entity_decode($description, ENT_QUOTES, 'UTF-8')));
    
    var_dump(urlencode($output)); // string(6) "%C2%A0"
    
    // -------
    
    $output = preg_replace('~^\s+|\s+$~', '', strip_tags(html_entity_decode($description, ENT_QUOTES, 'UTF-8')));
    
    var_dump(urlencode($output)); // string(6) "%C2%A0"
    
    // -------
    
    $output = preg_replace('~^\s+|\s+$~u', '', strip_tags(html_entity_decode($description, ENT_QUOTES, 'UTF-8')));
    // Unicode! -----------------------^
    
    var_dump(urlencode($output)); // string(0) ""
    

    正则表达式验尸

    • ~ - 正则表达式修饰符分隔符 - 必须在正则表达式之前,然后在修饰符之前
    • ^\s+ - 字符串的开头紧跟一个或多个空格(字符串开头的一个或多个空格字符) - ^ 表示字符串的开头,\s 表示空格字符, + 表示“匹配 1 到无限次”)
    • | - 或
    • \s+$ - 一个或多个空格字符紧跟在字符串末尾(字符串末尾有一个或多个空格字符)
    • ~ - 结束正则表达式修饰符分隔符
    • u - 正则表达式修饰符 - 这里使用 unicode modifier (PCRE_UTF8) 来确保我们替换 unicode 空白字符。

    【讨论】:

    • 尸检在这种情况下是一个很棒的词。
    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 2011-09-10
    • 2010-11-05
    • 2013-01-04
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多