I have a text string in the following format
$str= "word1 word2 word3 word4 ";
So I want to separate each word from the string. Two words are separated by a blank space How do I do that? Is there any built-in function to do that?
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
A delimiter is a character used to separate items in a string. In CSV or comma separated value format, a comma is used as a delimeter. It would appear that your first string is a space delimited string as it is a single string with several words all separated by spaces.
Split using $IFS variable $IFS variable is called 'Internal Field Separator' which determines how Bash recognizes boundaries. $IFS is used to assign the specific delimiter [ IFS=' ' ] for dividing the string. The white space is a default value of $IFS. However, we can also use values such as '\t', '\n', '-' etc.
The easiest would be to use explode
:
$words = explode(' ', $str);
But that does only accept fixed separators. split
an preg_split
do accept regular expressions so that your words can be separated by multiple spaces:
$words = split('\s+', $str);
// or
$words = preg_split('/\s+/', $str);
Now you can additionally remove leading and trailing spaces with trim
:
$words = preg_split('/\s+/', trim($str));
$words = explode( ' ', $str );
See: http://www.php.net/explode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With