2015-11-03 152 views
2

我试图用strip_tagstrim来检测一个字符串是否包含空html?PHP的html_entity_decode和修剪混淆

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

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

var_dump($output); 

字符串 'A'(长度= 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> 

回答

4

如果您使用var_dump(urlencode($output))你会看到它输出string(6) "%C2%A0",因此charcodes是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至无穷大时间“)
  • | - OR
  • \s+$ - 结束 - 随后立即串的端部(一端或在字符串的末尾)更多空白字符
  • ~的一个或多个空格字符正则表达式修饰符分隔符
  • u - 正则表达式修饰符 - 在这里使用unicode modifier (PCRE_UTF8)来确保我们替换unicode空白字符。
+1

尸体解剖在这方面是一个很棒的词。 – Martin