Split sentence into words

蓝咒 提交于 2019-12-01 10:56:57

问题


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...


回答1:


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

$words = explode(" ", $text);



回答2:


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
)



回答3:


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);


来源:https://stackoverflow.com/questions/18133857/split-sentence-into-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!