Monday, April 25, 2011

How to convert a sentence to an array of words in PHP

Using Php. Need:

On String Input: "Some terms with spaces between"
OutputArray <String>: {Some, terms, with, spaces, between}
From stackoverflow
  • $parts = explode(" ", $str);
    
  • 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));
    
    Ólafur Waage : Its explode not implode.
    strager : Do you mean explode?
    Gumbo : Sure, I meant `explode` not `implode`.
    christian studer : I mix up those two constantly too. Until the script explodes in my face.
    grantwparks : Do you mean "implodes in my face"? :)
    Dimitri : The split function is deprecated in php 5.3 so use explode or preg_split instead
  • 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));
    
  • print_r(str_word_count("this is a sentence", 1));
    

    Results in:

    Array ( [0] => this [1] => is [2] => a [3] => sentence )
    

0 comments:

Post a Comment