How to split string by space in PHP?

Member

by lew , in category: PHP General , 2 years ago

How to split string by space in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brandy , 2 years ago

@lew 

To split a string by space in PHP, you can use the explode() function. This function takes two arguments: the string to split and the delimiter to split it by. For example:

1
2
3
4
$string = "This is a string";

// Split the string by space
$parts = explode(" ", $string);

This will split the string into an array of parts, with each element containing one word from the original string. You can then access each part of the string using the array indexes, like this:

1
2
3
4
echo $parts[0]; // Outputs: "This"
echo $parts[1]; // Outputs: "is"
echo $parts[2]; // Outputs: "a"
echo $parts[3]; // Outputs: "string"

Alternatively, you can use the preg_split() function to split a string by space in PHP. This function takes a regular expression as the delimiter, so you can use the s pattern to match any whitespace characters, including spaces, tabs, and newlines. For example:

1
2
3
4
$string = "This is a string";

// Split the string by space
$parts = preg_split("/s/", $string);

This will give you the same result as using explode(), but using a regular expression as the delimiter allows for more flexibility and control over the split. For example, you could use the s+ pattern to match one or more consecutive whitespace characters, which would allow you to split a string by multiple spaces or other whitespace characters.

Member

by jerad , a year ago

@lew 

In PHP, you can split a string by space using the explode() function or the str_word_count() function. Here's how you can use both methods:


Method 1: Using explode()

1
2
3
4
5
$string = "Hello World PHP";
$words = explode(" ", $string);

// Output: Array ( [0] => Hello [1] => World [2] => PHP )
print_r($words);


In this method, the explode() function splits the $string into an array of words based on the space character as the delimiter.


Method 2: Using str_word_count()

1
2
3
4
5
$string = "Hello World PHP";
$words = str_word_count($string, 1);

// Output: Array ( [0] => Hello [1] => World [2] => PHP )
print_r($words);


In this method, the str_word_count() function counts the words in the $string and returns an array of the words.


Both methods return an array of words: Array ( [0] => Hello [1] => World [2] => PHP ). You can then iterate over this array to process or display each word individually.