Florian.C Florian.C - 1 year ago 75
PHP Question

Split a string every time it reaches 4 digits using regular expressions

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


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


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 Source

You don't want preg_split, you want preg_match_all:

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


array(1) {
  array(3) {
    string(9) "ABCDE1234"
    string(8) "ABCD1234"
    string(10) "ABCDEF1234"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download