I have a string like this: (...1 (...2 DS(...3 ( ...4 ) ) ) )
Which the best idea to find data in DS brackets if I don't know how much brackets after DS before it end? (3, 4) Its like math: multiply ds on the 3 and 4 brackets.
It can not be done by regular expression. Its not a regular language. Its general parsing.
$data = '(...1 (...2 DS(...3 ( ...4 ) 5) )6 )';
$num = array();
$start = strpos($data, 'DS') + strlen('DS');
$end = strlen($data) - 1;
$paren = 0;
for ($i = $start;$i <= $end;$i++) {
$n = $data[$i];
if ($n == '(') $paren++;
if ($n == ')') $paren--;
if ($paren >= 0 && is_numeric($n)) {
$num[] = $n;
}
}
print_r($num);
output
Array
(
[0] => 3
[1] => 4
[2] => 5
)
It's not possible using regex. Regex is unable to save how many open parentheses are there...
You should code it by php.
Take the substring from the place where DS occurs using the function substr, and get the data out of it. To get the data, just parse the substring keeping a count of opening brackets. When the closing brackets start, keep a count of them. When this count and previous count become equal, you have got your data.
does this work with it?
preg_match_all('/DS\(...(\d)+ \)?\(?[DS]?/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];