所述str_word_count()函数返回保持字符串中的所有字阵列.除了使用特殊字符外,它的效果很好.在这种情况下,php脚本通过querystring接收字符串:
当我打开: http://localhost/index.php?q = this%20wórds
header('Content-Type: text/html; charset=utf-8');
print_r(str_word_count($_GET['q'],1,'ó'));
Run Code Online (Sandbox Code Playgroud)
而不是返回:
[0] this
[1] wórds
Run Code Online (Sandbox Code Playgroud)
......它返回:
[0] this
[1] w
[2] rds
Run Code Online (Sandbox Code Playgroud)
该函数如何支持通过查询字符串发送的特殊字符?
更新 - 通过使用马里奥的解决方案,效果很好:
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];
}
Run Code Online (Sandbox Code Playgroud)
mar*_*rio 11
不确定第三个参数是否足以使str_word_count
非ASCII符号起作用.它可能只适用于Latin-1
任何事情.
作为替代方案,您可以使用正则表达式计算单词:
$count = preg_match_all('/\pL+/u', $_GET['q'], $matches);
Run Code Online (Sandbox Code Playgroud)
这至少适用于UTF-8.要完全复制str_word_count
,[\pL']+
最终可能需要.