Tuesday, January 28, 2014

PHP - divide strings into array or words



In PHP, we can use explode to divide strings into array or words.
For example:
< ?php
                $namestring = "Jiansen Lu";
                $namearray  =  explode(" ", trim($namestring));
                var_dump($namearray);

?>
Result:
array(2) { [0]=> string(7) "Jiansen" [1]=> string(2) "Lu" } 

But this may cause problem when there are two or more spaces between words, for example:

< ?php
                $namestring = "Jiansen  Lu";//Two spaces between words
                $namearray  =  explode(" ", trim($namestring));
                var_dump($namearray);

?>
Result:
 array(3) { [0]=> string(7) "Jiansen" [1]=> string(0) "" [2]=> string(2) "Lu" }
The second element, i.e. [1] is no more Lu, but is an empty string.

To resolve problem for two or more space in explode function, it is better to  use regular expression.
Example
< ?php
                $namestring = "Jiansen  Lu";//Two spaces between words
               
$namearray = preg_split('/\s+/',trim($namestring));
                var_dump($namearray);

?>
Result:
 array(2) { [0]=> string(7) "Jiansen" [1]=> string(2) "Lu" }

No comments:

Post a Comment