Florian.C Florian.C - 1 month ago 5
PHP Question

Split a string everytime it reaches 4 digits using Regular Expressions

I am trying to split a string in php, wich looks like this :

ABCDE1234ABCD1234ABCDEF1234


Into an array of string which, in this case, would look like this :

ABCDE1234
ABCD1234
ABCDEF1234


So the pattern is "an undefined number of letters, and then 4 digits, then an undefined number of letters and 4 digits etc."

I'm trying to split the string using preg_split like this :

$pattern = "#[0-9]{4}$#";
preg_split($pattern, $stringToSplit);


And it returns an array containing the full string (not split) in the first element.

I'm guessing the problem here is my regex as I don't fully understand how to use them, and I am not sure if I'm using it correctly.

So what would be the correct regex to use ?

Answer

You don't want preg_split, you want preg_match_all:

$str = 'ABCDE1234ABCD1234ABCDEF1234';
preg_match_all('/[a-z]+[0-9]{4}/i', $str, $matches);
var_dump($matches);

Output:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(9) "ABCDE1234"
    [1]=>
    string(8) "ABCD1234"
    [2]=>
    string(10) "ABCDEF1234"
  }
}
Comments