1

I am trying to split a string like this:

$string = letters1234_1-someMoreText;

Output should be:

$string_split [letters1234, 1, someMoreText];

Only if string matches the desired patern.

if(preg_match('/^([A-Z]+)([0-9])([_])([0-9])([-])/', $string)) {
       $string_split = preg_split('/^([A-Z]+[0-9]+)([_])([0-9])([-])([A-Z]+[0-9]+)/', $string);
}else{
       $string_split = $string;
}

This seems to be much more complicated than I have comprehend by now, but so far being stuck..

1 Answers1

1

You may actually use your current regex (and add .* to it to match the string tail) with a preg_match function and use capturing groups to capture the parts you need to get as a result. In your case, just check with preg_match and once a match is found, assign the found captures to the $string_split variable:

$string = "letters1234_1-someMoreText";
$string_split = $string;
if (preg_match('/^([A-Z]+[0-9]+)_([0-9])-(.*)/si', $string, $matches)) {
    array_shift($matches);
    $string_split = $matches;
}
print_r($string_split);

See the PHP demo yielding

Array
(
    [0] => letters1234
    [1] => 1
    [2] => someMoreText
)

Pattern details

  • ^ - start of string
  • ([A-Z]+[0-9]+) - Capturing group 1: one or more letters followed with 1+ digits
  • _ - an underscore
  • ([0-9]) - Capturing group 2: a digit
  • - - a hyphen
  • (.*) - any 0+ chars

The is modifiers make the pattern case insensitive and . may match line break chars.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563