I have a string of numbers surrounded by parenthesis:
(2)(56)(9)(12)(2)
I was given the following regex by someone to split the numbers out of their parentheses:
<?php
$string = '(2)(56)(9)(12)(2)';
$pattern = "/\\)\\(|\\(|\\)?/";
$numbers = preg_split($pattern, $string);
foreach ($numbers as $number) {
echo $number.'<br />';
}
?>
This outputs:
<br />
<br />
2<br />
<br />
5<br />
6<br />
<br />
9<br />
<br />
1<br />
2<br />
<br />
2<br />
<br />
<br />
When I really need it to output:
2<br />
56<br />
9<br />
12<br />
2<br />
How can the regex be altered to make it work?
p.s. each number in between the parenthesis can be of an unlimited length.
You just need the PREG_SPLIT_NO_EMPTY option of preg_split, and a small change in the pattern:
Or use preg_match:
Output: