Milan Maharjan
Milan Maharjan

Reputation: 4246

split string whenever there are 5 spaces

I have a string like this

ADBL 489 ( 156 ) (  33 )     AHPC 434 ( 243 ) (  4 )     AIC 715 ( 200 ) (  50 )

I want to split this into three strings:

Between them are 5 spaces. How can I achieve this using regular expressions in PHP. I tried this, but its not working:

$splited_string = preg_split('/\s\s\s\s\s/', $string);

Upvotes: 2

Views: 84

Answers (3)

Martijn
Martijn

Reputation: 16113

php.net / explode

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

$array = explode("     ", $string);

If you want it back to the string again, you can use implode:

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

$string = implode(" and ", $array);

If you want the 5(or more) spaces replaced with something else:

$string = preg_replace("/\s{5,}/", " and ", $string); // {5} will make exact 5

You should be carefull with regexes. It's a powerfull tool, but you should only equip the big guns when the lightweight options are none. In the examples above, this would be faster because arrays for stringmanipulation rarely pay off.

Upvotes: 3

user3599730
user3599730

Reputation: 136

something like this:

$pizza="ADBL 489 ( 156 ) (  33 )     AHPC 434 ( 243 ) (  4 )     AIC 715 ( 200 ) (  50 )";
$parts=explode("     ", $pizza);
echo $parts[0]; // ADBL 489 ( 156 ) (  33 )
echo $parts[1]; // AHPC 434 ( 243 ) (  4 )

Upvotes: 3

Karl
Karl

Reputation: 833

This would work.

$str = 'ADBL 489 ( 156 ) (  33 )     AHPC 434 ( 243 ) (  4 )     AIC 715 ( 200 ) (  50 )';
$strings = explode('     ', $str);
print_r($strings);

Upvotes: 1

Related Questions