Skip to content
Advertisement

PHP: Best way to “explode” string based on regex / find elements between regex maches

Lets say I have a string such as:

155+44x3/2-12

How can I split it up so that the end result would be:

$numbers = [155, 44, 3, 2, 12];
$operators = ['+', 'x', '/', '-'];

I can get one or the other separately fairly easily using regex, but is there a good way to get the numbers using regex and then get “the rest” into another variable without writing explicit regex for it? The array items should be correctly ordered as per the initial string.

Or two separate regex clauses would be the best in this case? E.g.

preg_match_all($string, "/(d+)/", $numbers);
preg_match_all($string, "/(D+)/", $rest);

Advertisement

Answer

You may be able to do this in a single preg_match_all call with 2 capture groups in this regex:

(d+)(D*)

Which matches 1+ digits in capture group #1 and matches 0 or more non-digits in capture group #2

RegEx Demo

$s = '155+44x3/2-12';
if (preg_match_all('/(d+)(D*)/', $s, $m)) {
   $numbers = $m[1];
   $operators = array_filter($m[2]);
   // print arrays
   print_r($numbers);
   print_r($operators);
}

Output:

Array
(
    [0] => 155
    [1] => 44
    [2] => 3
    [3] => 2
    [4] => 12
)
Array
(
    [0] => +
    [1] => x
    [2] => /
    [3] => -
)

array_filter has been used to filter out empty elements from array.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement