dououde4065 2015-11-03 11:59
浏览 49
已采纳

PHP html_entity_decode和修剪混乱

I'm trying to use strip_tags and trim to detect if a string contains empty html?

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

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

var_dump($output);

string 'Â ' (length=2)

My debug to try figure this out:

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

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

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

Output: debug.txt

ASCII
 
<p> </p>
  • 写回答

1条回答 默认 最新

  • duangu1033 2015-11-03 12:07
    关注

    If you use var_dump(urlencode($output)) you'll see that it outputs string(6) "%C2%A0" hence the charcodes are 0xC2 and 0xA0. These two charcodes are unicode for "non-breaking-space". Make sure your file is saved in UTF-8 format and your HTTP headers are UTF-8 format.

    That said, to trim this character you can use regex with the unicode modifier (instead of trim):

    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) ""
    

    Regex autopsy:

    • ~ - the regex modifier delimiter - must be before the regex, and then before the modifiers
    • ^\s+ - the start of the string immediately followed by one or more whitespaces (one or more whitespace characters in the start of the string) - (^ means start of the string, \s means a whitespace character, + means "matched 1 to infinity times")
    • | - OR
    • \s+$ - one or more whitespace characters immediately followed by the end of the string (one or more whitespace characters in the end of the string)
    • ~ - the ending regex modifier delimiter
    • u - the regex modifier - here using the unicode modifier (PCRE_UTF8) to make sure we replace unicode whitespace characters.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?