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
- How to blend adsense inside your post?
- Formatting my post
- Notepad++ - Add C++ compiler
- Install PHPMailer 5.2.4 and use smtp gmail
- Set up a child account and set screen time limit in Windows 8
- Wayback Machine - see archived versions of web pages across time
- phpexcel toggle expand and hide column in EXCEL and summary
- Install PHP ibm_db2 extension in Linux (redHat)
- PHP: add a download as pdf file button in report page
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