Online computer courses, code, programming tutorial and sidebar information for monitoring Canadian S&P/TSX index. Build friendship and networking. Welcome to visit my blogs often!!! I also have two other sites: YouTube Channel and Google site.
Adsense
Popular Posts
- PHPWind-- A PHP forum script applcaition in China
- Free host forum is not reliable
- Formatting my post
- Powerful js library datable to export table in pdf, excel, sorting, freezing column and table header fixed (sticky)
- job interview questions (1)
- Set up a child account and set screen time limit in Windows 8
- PHP: add a download as pdf file button in report page
- phpexcel toggle expand and hide column in EXCEL and summary
- WinMerge - file and folder differencing and merging tool for Windows
- PHP connect IBM db2 database in XAMPP
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" }
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment