Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

From this string:

$input = "Some terms with spaces between";

how can I produce this array?

$output = ['Some', 'terms', 'with', 'spaces', 'between'];
like image 788
Duncan Avatar asked Mar 06 '09 12:03

Duncan


1 Answers

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));
like image 135
Gumbo Avatar answered Oct 24 '22 15:10

Gumbo