How can I convert a sentence to an array of words?

后端 未结 5 1033
故里飘歌
故里飘歌 2020-12-19 04:49

From this string:

$input = \"Some terms with spaces between\";

how can I produce this array?

$output = [\'Some\', \'terms\'         


        
相关标签:
5条回答
  • 2020-12-19 05:14
    $parts = explode(" ", $str);
    
    0 讨论(0)
  • 2020-12-19 05:19

    You could use explode, split or preg_split.

    explode uses a fixed string:

    $parts = explode(' ', $string);
    

    while split and preg_split use a regular expression:

    $parts = split(' +', $string);
    $parts = preg_split('/ +/', $string);
    

    An example where the regular expression based splitting is useful:

    $string = 'foo   bar';  // multiple spaces
    var_dump(explode(' ', $string));
    var_dump(split(' +', $string));
    var_dump(preg_split('/ +/', $string));
    
    0 讨论(0)
  • 2020-12-19 05:19

    Just a question, but are you trying to make json out of the data? If so, then you might consider something like this:

    return json_encode(explode(' ', $inputString));
    
    0 讨论(0)
  • 2020-12-19 05:21

    Just thought that it'd be worth mentioning that the regular expression Gumbo posted—although it will more than likely suffice for most—may not catch all cases of white-space. An example: Using the regular expression in the approved answer on the string below:

    $sentence = "Hello                       my name    is   peter string           splitter";
    

    Provided me with the following output through print_r:

    Array
    (
        [0] => Hello
        [1] => my
        [2] => name
        [3] => is
        [4] => peter
        [5] => string
        [6] =>      splitter
    )
    

    Where as, when using the following regular expression:

    preg_split('/\s+/', $sentence);
    

    Provided me with the following (desired) output:

    Array
    (
        [0] => Hello
        [1] => my
        [2] => name
        [3] => is
        [4] => peter
        [5] => string
        [6] => splitter
    )
    

    Hope it helps anyone stuck at a similar hurdle and is confused as to why.

    0 讨论(0)
  • 2020-12-19 05:40
    print_r(str_word_count("this is a sentence", 1));
    

    Results in:

    Array ( [0] => this [1] => is [2] => a [3] => sentence )
    
    0 讨论(0)
提交回复
热议问题