If I have a string like this:
$string = "number: 20 (10 30 10 zzz) 40 60";
How do I match all numbers outside the parentheses?
I would like to get only
20,40,60
If I have a string like this:
$string = "number: 20 (10 30 10 zzz) 40 60";
How do I match all numbers outside the parentheses?
I would like to get only
20,40,60
Here is a preg_split()
approach:
Input:
$string = "number: 20 (10 30 10 zzz) 40 60";
One-liner (Pattern Demo):
var_export(preg_split('/ |number: |\([^)]*\)/', $string, 0, PREG_SPLIT_NO_EMPTY));
Output:
array (
0 => '20',
1 => '40',
2 => '60',
)
This pattern will explode on:
number:
Edits:
This pattern also works with preg_split()
: /[ a-z:]+|\([^)]*\)/i
It is slightly faster.
...
chris85's commented pattern for preg_match()
is correct. I have optimized it by reversing the alternatives: \d+|\([^)]+\)(*SKIP)(*FAIL)