php - 使用 str_word_count() 支持特殊字符

标签 php utf-8

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/

相关文章:

php - 关于array_udiff,我想再问一下

XAMPP Windows 上的 Php Cron 作业

php - 如何在 PHP 中解码邮件标题字符串及其编码类型

mysql - Rails 3 ruby 1.9.2 : UTF-8 characters show garbled in console and view

c - 如何检测ODBC DB2连接编码(代码页)

php - Facebook OAuthException : "user hasn' t authorized the application to perform this action"

php - 在Mysql中过滤数据

PHP json_encode 变音符号

php - 在 for 循环中从数组中获取值以在 MySQL 中使用

java - 将元素标签替换为空标签