33

I have an input where a user may type in multiple words, and they are told to separate it with a space. So input may look like this:

foo

or like this:

foo bar php js

How can I check for spaces, and if there are spaces, split the words, then put it all into an array? I'll loop through that array in my program. I'm just new to string handling like this.

Braiam
  • 1
  • 11
  • 47
  • 78
AKor
  • 8,550
  • 27
  • 82
  • 136

7 Answers7

103

See explode

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
14

Yes explode will do every thing for you and foreach can be used to retrieve the values from the array again. Your complete code will be something like following one:

$str = "foo bar php js";
$arr =  explode(" ", $str);

//print all the value which are in the array
foreach($arr as $v){
    echo $v;
}

Hope this will help you.

enam
  • 1,179
  • 1
  • 10
  • 24
5

Daniel has already posted about the splitting part, let me add the checking for space part also.

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pizza = trim($pizza);

if(strpos($pizza, " ") !== false)

    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2

}else{

    echo $pizza;

}
weekapaug
  • 332
  • 1
  • 4
  • 15
Mr Coder
  • 8,169
  • 5
  • 45
  • 74
  • Its old but this didnt work to detect the blank space - I had to use if(strpos($pizza, " ") !== false); I edited the original post so comment may become redundant – weekapaug Sep 14 '18 at 21:44
  • 1
    In case you use this script for separating input values from a form and want to make sure there is only 1 white space between the names, e.g. wenn having a namestring to split into fristname + secondname + lastname. then use the following transformation first: $pizza = preg_replace('!\s+!', ' ', $pizza); So you get nice single white space separated words I can explode into array values. – nh-labs Sep 22 '20 at 15:49
5

Your sample input is relatively calm. If you are trusting your users to perfectly enter qualifying substrings which are always delimited by exactly one space, then the best choice is explode().

If the user input can vary beyond just lowercase letters or you want to validate while extracting, there are other more appropriate functions to call.

Understanding you business logic will determine the best solution for this task.

A demonstration:

$input = "foo bar, php js  double-space apo'strophe 9 ";

echo 'explode(): '; var_export(explode(' ', $input));

echo "\npreg_split(): "; var_export(preg_split('/ +/', $input, null, PREG_SPLIT_NO_EMPTY));

echo "\nstr_word_count(): "; var_export(str_word_count($input, 1));

echo "\npreg_match_all(): "; var_export(preg_match_all('/[a-z]+/', $input, $output) ? $output[0]: []);

Output:

explode(): array (
  0 => 'foo',
  1 => 'bar,',
  2 => 'php',
  3 => 'js',
  4 => '',
  5 => 'double-space',
  6 => 'apo\'strophe',
  7 => '9',
  8 => '',
)
preg_split(): array (
  0 => 'foo',
  1 => 'bar,',
  2 => 'php',
  3 => 'js',
  4 => 'double-space',
  5 => 'apo\'strophe',
  6 => '9',
)
str_word_count(): array (
  0 => 'foo',
  1 => 'bar',
  2 => 'php',
  3 => 'js',
  4 => 'double-space',
  5 => 'apo\'strophe',
)
preg_match_all(): array (
  0 => 'foo',
  1 => 'bar',
  2 => 'php',
  3 => 'js',
  4 => 'double',
  5 => 'space',
  6 => 'apo',
  7 => 'strophe',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
1

For optimization purposes, i think its better to remove excess spaces like double spaces before using explode function. for example: if you have "foo bar php js " this string must become "foo bar php js" before using explode function. you may try this code:

$charSet = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $charSet);
$charSet = rtrim($charSet);
$charSetArray = explode(" ", $charSet);
echo $charSetArray[0];
echo $charSetArray[1];
Jemuel Elimanco
  • 416
  • 2
  • 4
  • 20
0

As Daniel said, explode() is perfect for this kind of situation. You may also want to look at preg_split() (purely for future reference) as it accepts a regex rather than just a simple delimiter and will allow you to break up input on a more complex pattern.

Endophage
  • 21,038
  • 13
  • 59
  • 90
  • 2
    `split` is deprecated and should be avoided. If you need regex, use `preg_split` instead... – ircmaxell Feb 16 '11 at 18:03
  • @ircmaxell Updated to reflect that. It's unfortunate that production environments tend to run behind the latest version, I forget that some things are deprecated in 5.3 – Endophage Feb 16 '11 at 18:32
0

This will work if there is no space between the input string.`

    $pieces = explode(" ", $pizza);
    if(count($pieces > 1)) {
        foreach($pieces as $piece) {
            echo $piece;
        }
    }
    else {
        echo $userInput;
    }
?>`

Explanation :
After exploding the string into pieces. Firstly it checks if we have more items in array i.e. $pieces if yes it will print via foreach loop otherwise it will simply print the user input.

Shanteshwar Inde
  • 1,438
  • 4
  • 17
  • 27