php - 将文本拆分为单个单词

标签 php split

我想使用 PHP 将文本拆分为单个单词。您知道如何实现这一目标吗?

我的方法:

function tokenizer($text) {
    $text = trim(strtolower($text));
    $punctuation = '/[^a-z0-9äöüß-]/';
    $result = preg_split($punctuation, $text, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0; $i < count($result); $i++) {
        $result[$i] = trim($result[$i]);
    }
    return $result; // contains the single words
}
$text = 'This is an example text, it contains commas and full-stops. Exclamation marks, too! Question marks? All punctuation marks you know.';
print_r(tokenizer($text));

这是一个好方法吗?你有什么改进的想法吗?

提前致谢!

最佳答案

使用匹配任何 unicode 标点字符的类\p{P},结合\s 空白类。

$result = preg_split('/((^\p{P}+)|(\p{P}*\s+\p{P}*)|(\p{P}+$))/', $text, -1, PREG_SPLIT_NO_EMPTY);

这将拆分一组一个或多个空白字符,但也会吸收周围的任何标点符号。它还匹配字符串开头或结尾的标点符号。这区分了诸如“不要”和“他说‘哎哟!’”之类的情况

关于php - 将文本拆分为单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/790596/

相关文章:

php - Laravel 数据表中的限制

php - 教义实体未保存,但具有自动增量 id

php - 在 PHP 中替换表情符号的更好方法?

java - 在“>”上分割长字符串

java字符串拆分(字符串,整数)

java - 将文本文件转为数组

python - split() 字符串上的 Python strip() 有什么作用吗?

php imagick,如何使区域透明

php - 将用户 ID 存储或获取为 PHP session 变量

python - 如何在 Python 中拆分字符串,直到从右到左出现特定字符之一?