str_word_count() for non-latin words?(str_word_count() 用于非拉丁词?)
问题描述
我正在尝试计算用非拉丁语言(保加利亚语)编写的变量中的单词数.但似乎 str_word_count() 没有计算非拉丁词.php文件的编码为UTF-8
im trying to count the number of words in variable written in non-latin language (Bulgarian). But it seems that str_word_count() is not counting non-latin words. The encoding of the php file is UTF-8
$str = "текст на кирилица";
echo 'Number of words: '.str_word_count($str);
//this returns 0
推荐答案
您可以使用正则表达式:
You may do it with regex:
$str = "текст на кирилица";
echo 'Number of words: '.count(preg_split('/s+/', $str));
这里我将单词定界符定义为空格字符.如果可能还有其他东西将被视为单词分隔符,您需要将其添加到您的正则表达式中.
here I'm defining word delimiter as space characters. If there may be something else that will be treated as word delimiter, you'll need to add it into your regex.
另外,请注意,由于在正则表达式中没有 utf 字符 (不在字符串中) - /u
修饰符不是必需的.但是如果你想要一些 utf 字符作为分隔符,你需要添加这个正则表达式修饰符.
Also, note, that since there's no utf characters in regex (not in string) - /u
modifier isn't required. But if you'll want some utf characters to act as delimiter, you'll need to add this regex modifier.
更新:
如果您只想在文字中处理 西里尔文 字母,您可以使用:
If you want only cyrillic letters to be treated in words, you may use:
$str = "текст
на 12453
кирилица";
echo 'Number of words: '.count(preg_split('/[^А-Яа-яЁё]+/u', $str));
这篇关于str_word_count() 用于非拉丁词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:str_word_count() 用于非拉丁词?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01