Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate space-delimited words in a string

Tags:

string

php

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?

like image 237
user177785 Avatar asked Sep 26 '09 12:09

user177785


People also ask

How do I split a string into multiple spaces?

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.

What is space delimited string?

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.

How do you split a space in bash?

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.


2 Answers

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));
like image 152
Gumbo Avatar answered Oct 01 '22 14:10

Gumbo


$words = explode( ' ', $str );

See: http://www.php.net/explode

like image 43
Rob Avatar answered Oct 01 '22 14:10

Rob