Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array from a string separated by spaces

Tags:

php

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.

like image 574
AKor Avatar asked Feb 16 '11 17:02

AKor


People also ask

How do you split a string into an array by spaces?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you convert spaces separated integers into arrays in Java?

split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.

How split a string by space in C#?

C# allows to split a string by using multiple separators. var text = "falcon;eagle,forest,sky;cloud,water,rock;wind"; var words = text. Split(new char[] {',', ';'}); Array. ForEach(words, Console.


2 Answers

See explode

// Example 1 $pizza  = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 
like image 106
Daniel A. White Avatar answered Sep 28 '22 03:09

Daniel A. White


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.

like image 43
enam Avatar answered Sep 28 '22 04:09

enam