Search code examples
phparraysdelimiterexplodesubstring

How to explode and keep white space in strings?


I have a series of country names like:

United Kingdom Spain Russia Saudi Arabia

The thing is if I do:

$stateList = explode(' ', $stateList);

That will result in:

United KingdomSpainRussiaSaudi Arabia

UPDATE

This is what I am doing aftwards:

foreach($stateList as $state) { echo $state;

But the result is as per above


Solution

  • You will not be able to differentiate between spaces within country names and spaces as country delimiters.

    You could modify your input array and use explode():

    $state_list='United Kingdom,Spain,Russia,Saudi Arabia';
    
    foreach(explode(',',$state_list) as $state){
        echo $state,"<br>";
    }