word [1] => word [-6ren">
gpt4 book ai didi

php - 把句子拆成单词

转载 作者:行者123 更新时间:2023-12-05 08:17:38 25 4
gpt4 key购买 nike

例如我有这样的句子:

$text = "word, word w.d. word!..";

我需要这样的数组

Array
(
[0] => word
[1] => word
[2] => w.d
[3] => word".
)

我对正则表达式很陌生..

这是我尝试过的:

function divide_a_sentence_into_words($text){ 
return preg_split('/(?<=[\s])(?<!f\s)\s+/ix', $text, -1, PREG_SPLIT_NO_EMPTY);
}

这个

$text = "word word, w.d. word!..";
$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($split);

有效,但我有第二个问题,我想用 mu 正则表达式编写列表"w.d"是特殊情况.. 例如这个词是我的列表 "w.d", "mr.", "dr."

如果我要文字:

$text = "word, dr. word w.d. word!.";

我需要数组:

Array (
[0] => word
[1] => dr.
[2] => word
[3] => w.d
[4] => word
)

抱歉英语不好...

最佳答案

使用 preg_split 和正则表达式 /[^\w]*([\s]+[^\w]*|$)/ 应该可以正常工作:

<?php
$text = "word word w.d. word!..";
$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($split);
?>

DEMO

输出:

Array
(
[0] => word
[1] => word
[2] => w.d
[3] => word
)

关于php - 把句子拆成单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18133857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com