3zzy 3zzy - 11 days ago 8
PHP Question

Splitting a string inside brackets

I need a string

VN7-572G-75AJ(NX.G6GSA.001)
to be split in an array like so:

[0] => VN7-572G-75AJ
[1] => NX.G6GSA.001


.. but I can't get the matching groups right:

$str = 'VN7-572G-75AJ(NX.G6GSA.001)';
preg_match('#\(/[^(]*/\) \((.*?)\)#', $str, $matches);
echo print_r($matches ,1); // outputs empty array

Answer

A totally non-regex solution is possible:

$str = 'VN7-572G-75AJ(NX.G6GSA.001)';
echo strstr($str, '(', true);       // Part 1
echo "\n";
echo trim(strstr($str, '('), '()'); // Part 2

See the PHP demo. The first VN7-572G-75AJ part can be easily obtained with strstr (the true argument is the $before_needle value, we need all before the char indicated) and the second one gets all the substring from the first ( till the end, and then trim helps remove the ( and ) from the initial and trailing positions.

If you want your regex fixed, here is a solution:

$str = 'VN7-572G-75AJ(NX.G6GSA.001)';
preg_match('#^([^(]*)\(([^()]*)\)$#', $str, $matches);
echo $matches[1] . "\n" . $matches[2];

Here is a PHP demo

Details:

  • ^ - start of string
  • ([^(]*) - Group 1: zero or more symbols other than (
  • \( - a literal (
  • ([^()]*) - Group 2: 0+ chars other than ( and )
  • \) - a literal ) symbol
  • $ - end of string.

Another - simpler regex way - is to match any 1+ chars other than ( and ):

preg_match_all('#[^()]+#', $str, $matches);
echo $matches[0][0] . "\n" . $matches[0][1];

See this PHP demo