str_word_count()函数返回一个数组,该数组包含字符串中的所有单词。它工作得很好,除非使用特殊字符。在这种情况下,php 脚本通过查询字符串接收字符串:
当我打开时: http://localhost/index.php?q=this%20wórds
header('Content-Type: text/html; charset=utf-8');
print_r(str_word_count($_GET['q'],1,'ó'));
而不是返回:
[0] this
[1] wórds
...它返回:
[0] this
[1] w
[2] rds
这个函数如何支持那些通过查询字符串发送的特殊字符?
更新 - 使用 mario 结果很好的解决方案:
function sanitize_words($string) {
preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u",$string,$matches,PREG_PATTERN_ORDER);
return $matches[0];
}
最佳答案
不确定第三个参数是否足以使 str_word_count
用于非 ASCII 符号。如果有的话,它可能只适用于 Latin-1
。
作为替代方案,您可以使用正则表达式计算字数:
$count = preg_match_all('/\pL+/u', $_GET['q'], $matches);
这至少适用于 UTF-8。要完全复制 str_word_count
,您最终可能需要 [\pL']+
。
关于php - 使用 str_word_count() 支持特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109997/