4

I try to split the string A1B22C333 to get the array [0] => A1 , [1] => B22, [2] => C333. This is my failed attempt:

$mystring = "A1B22C333";
$pattern  = "[\w\d+]";
$arr = preg_split("/".$pattern."/", $mystring);
print_r($arr);

But i get: Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )

rock321987
  • 10,292
  • 1
  • 23
  • 36
Black
  • 12,789
  • 26
  • 116
  • 196
  • Can someone help me rename the title of the question to prevent duplicates? EDIT: Thx rock321957 – Black Apr 18 '16 at 07:10

3 Answers3

3

You can use a regex like

(?<!^)(?=\D)

See the regex demo

The (?<!^)(?=\D) matches location not at the start of the string and before a non-digit character.

See the IDEONE demo:

$mystring = "A1B22C333";
$pattern  = '~(?<!^)(?=\D)~';
$arr = preg_split($pattern, $mystring);
print_r($arr);
// => Array( [0] => A1    [1] => B22    [2] => C333 )

You can also shorten the regex to a mere '~(?=\D)~' (position before a non-digit) if you use PREG_SPLIT_NO_EMPTY (demo):

$pattern  = '~(?=\D)~';
$arr = preg_split($pattern, $mystring, -1, PREG_SPLIT_NO_EMPTY);
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • I never saw the `~` char in a regex before, can someone explain for what it is used? – Black Apr 18 '16 at 07:17
  • 2
    A `~` is a regex delimiter, same as `/`, but as `/` is often used in the pattern (and then all `/` must be escaped in the pattern), a `~` is a more convenient delimiter to use. – Wiktor Stribiżew Apr 18 '16 at 07:20
  • Thats a good tipp, thank you @Wiktor, i will only use `~` now in the future. – Black Apr 18 '16 at 07:23
  • 1
    @EdwardBlack: Just do not forget to escape literal `~` inside the pattern then (*everywhere* inside the pattern). Also, your `[\w\d+]` did not work because it matches 1 alphanumeric or a literal `+` symbol, and when splitting a string that only consists of these characters, you get an expected array of multiple empty elements. – Wiktor Stribiżew Apr 18 '16 at 07:25
1

Instead of preg_split use preg_match_all along with following regex

([a-zA-Z]\d+)

So your code looks like as

preg_match_all("/([a-zA-Z]\d+)/","A1B22C333",$m);
print_r($m[0]);

Output :

Array
(
    [0] => A1
    [1] => B22
    [2] => C333
)
Narendrasingh Sisodia
  • 19,948
  • 5
  • 40
  • 50
1

I think you should use preg_match_all.

preg_match_all("/([A-Z]\d+)/", "A1B22C333", $output_array);

click on preg_match_all
http://www.phpliveregex.com/p/fnj

Andreas
  • 24,301
  • 5
  • 27
  • 57