2

例如我有这样的句子:

$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 正则表达式写列表“wd”是特例。例如,这个词是我的列表“wd”、“先生”、“博士”。

如果我要接受文字:

$text = "单词,博士单词 wd 单词!..";

我需要数组:

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

对不起英语不好...

4

3 回答 3

6

使用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);
?>

演示

输出:

Array
(
    [0] => word
    [1] => word
    [2] => w.d
    [3] => word
)
于 2013-08-08T19:01:37.100 回答
5

使用函数explode,它将字符串拆分成一个数组

$words = explode(" ", $text);
于 2013-08-08T18:55:24.017 回答
3

利用

str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

请参阅此处http://php.net/manual/en/function.str-word-count.php 它完全符合您的要求。所以在你的情况下:

$myarray = str_word_count ($text,1);
于 2013-08-08T18:57:56.313 回答