Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into into array of character pairs [duplicate]

Possible Duplicate:
PHP preg_split string into letter pairs

I have an string looking like this:

$str = "How are you doing?";

How can I turn this string into an array looking like this:

$arr = array("Ho","w ","ar","r ","yo","u ","do","in","g?");
like image 703
JNK Avatar asked Sep 14 '11 20:09

JNK


People also ask

How do you split a string into an array of letters?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

How do you split a string into an array in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


3 Answers

$array = str_split($str, 2);

Documentation.

like image 89
NikiC Avatar answered Oct 01 '22 09:10

NikiC


Use str_split() function.

like image 41
Crozin Avatar answered Oct 01 '22 10:10

Crozin


Take a look at str_split(); it allows you to split a string by a definable amount of characters, so your code would look like:

$arr = str_split($str, 2);

Which will split $str into an array $arr where each element contains two characters,

like image 37
Bojangles Avatar answered Oct 01 '22 08:10

Bojangles