tags:

views:

176

answers:

3

In PHP I'm trying to match each character as its own group. Which would mimic the str_split(). I tried:

$string = '123abc456def';
preg_match_all('/(.)*/', $string, $array);
// $array = array(2) { 
//   [0]=>  array(2) { 
//      [0]=>  string(12) "123abc456def"
//      [1]=>  string(0) "" } 
//   [1]=>  array(2) { [0]=>  string(1) "f" [1]=>  string(0) "" } }

I was expecting something like:

//$array = array(2) { 
//   [0]=> string(12) "123abc456def", 
//   [1]=> array(12) { 
//       [0]=>  string(1) "1", [1]=> string(1) "2"
//       ... 
//       [10]=> string(1) "e", [11]=> string(1) "f" } }

The reason I want to use the regular expression instead of a str_split() is because the regex will be the basis of another regex.

+4  A: 

The * outside the parens means you want to repeat the capturing group. (This means you will only capture the last iteration.) Try a global match of any single character, like this:

preg_match_all('/(.)/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
alphadogg
You can leave the parenthesis out.
Gumbo
True. Bad habit of being literal with any regex I compose... :)
alphadogg
A: 

Maybe this is what you are looking for:

preg_match_all('/(.)+?/', $string, $array);

Ch4m3l3on
+2  A: 

Try this:

preg_match_all('/./s', $str, $matches)

This does also match line break characters.

Gumbo