Split sentence into words

后端 未结 3 1679
我寻月下人不归
我寻月下人不归 2021-01-16 15:25

for example i have sentenes like this:

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

I need array like this

Array
(
    [0] => w         


        
相关标签:
3条回答
  • 2021-01-16 16:03

    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);
    
    0 讨论(0)
  • 2021-01-16 16:08

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

    $words = explode(" ", $text);
    
    0 讨论(0)
  • 2021-01-16 16:12

    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
    )
    
    0 讨论(0)
提交回复
热议问题