phpregexstringsplitpreg-split

Wrapping subpattern in square braces does not encapsulate the match as expected in regular expression


Regular exp = (Digits)*(A|B|DF|XY)+(Digits)+

I'm confused about this pattern really I want to separate this string in PHP, someone can help me My input maybe something like this

  1. A1234
  2. B 1239
  3. 1A123
  4. 12A123
  5. 1A 1234
  6. 12 A 123
  7. 1234 B 123456789
  8. 12 XY 1234567890

and convert to this

Array
(
    [0] => 12
    [1] => XY
    [2] => 1234567890
)

<?php
$input = "12    XY      123456789";
print_r(preg_split('/\d*[(A|B|DF|XY)+\d+]+/', $input, 3));
//print_r(preg_split('/[\s,]+/', $input, 3));
//print_r(preg_split('/\d*[\s,](A|B)+[\s,]\d+/', $input, 3));

Solution

  • You may match and capture the numbers, letters, and numbers:

    $input = "12    XY      123456789";
    if (preg_match('/^(?:(\d+)\s*)?(A|B|DF|XY)(?:\s*(\d+))?$/', $input, $matches)){
        array_shift($matches);
        print_r($matches);
    }
    

    See the PHP demo and the regex demo.