Split sentence into words

2019-02-20 03:56发布

for example i have sentenes like this:

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

I need array like this

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

I am very new for regular expression..

Here is what I tried:

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

this

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

works, but i have second question i want to write list in mu regular exppression "w.d" is special case.. for example this words is my list "w.d" , "mr.", "dr."

if i will take text:

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

i need array:

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

sorry for bad english...

3条回答
家丑人穷心不美
2楼-- · 2019-02-20 04:08

use

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

see here http://php.net/manual/en/function.str-word-count.php it does exactly what you want. So in your case :

$myarray = str_word_count ($text,1);
查看更多
Root(大扎)
3楼-- · 2019-02-20 04:26

Use the function explode, that will split the string into an array

$words = explode(" ", $text);
查看更多
【Aperson】
4楼-- · 2019-02-20 04:29

Using preg_split with a regex of /[^\w]*([\s]+[^\w]*|$)/ should work fine:

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

DEMO

Output:

Array
(
    [0] => word
    [1] => word
    [2] => w.d
    [3] => word
)
查看更多
登录 后发表回答