Kęstutis
Kęstutis

Reputation: 55

PHP regular expression get float value between brackets

I have a little problem with getting some numbers from a string.

For example I have this kind of str:

qweqeqe (qweqwe) AASD 213,21 ( -1201,77 EUR )

I need the numbers with comma that are between brackets Result: -1201,77 The value also can be positive. I have already managed to get float value, but from all string. I have this: !\d+(?:\,\d+)?! but it gets all numbers in a str.

Upvotes: 1

Views: 212

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

IF THERE IS ALWAYS 1 NUMBER INSIDE PARENTHESES...

Here is a two-pass, "readable" approach: extract all parenthetical substrings and then use preg_filter to extract the float values:

$s = "qweqeqe (qweqwe) AASD 213,21 ( -1201,77 EUR )";
preg_match_all('/\([^()]*\)/', $s, $parentheses);
$res = preg_filter('/.*?([+-]?\d+(?:,\d+)?).*/s', '$1', $parentheses[0]);
                     ^^^     ^

See IDEONE demo

Here, we match any symbols before and after float with .*. Note that to preserve the number, we need to use lazy dot matching in the left part (.*?), and we can match anything in the part after the number. As the +/- before the number are optional, use a ? quantifier: [-+]?.

IF THERE CAN BE MORE THAN 1 NUMBER INSIDE PARENTHESES...

It is a less readable one-pass approach:

$s = "qweqeqe (qweqwe) AASD 213,21 ( -1201,77 EUR )";
preg_match_all('/(?:\(|(?!^)\G)[^()]*?([+-]?\d+(?:,\d+)?)(?=[^()]*\))/', $s, $matches);
                                       ^^^^

See another IDEONE demo

Here, the regex defines the starting boundary with (?:\(|(?!^)\G) (that is, start looking for the numbers after ( and then after each successful match) and then capture the floats with [^()]*?(\d+(?:,\d+)?) but ensuring we are still inside the parentheses (the rightmost boundary is checked with the (?=[^()]*\)) lookahead).

Upvotes: 2

Halayem Anis
Halayem Anis

Reputation: 7805

try this pattern :

$pattern = "#\([\s]*(-{0,1}[0-9]+,[0-9]+)[\s]*[A-Za-z]*[\s]*\)#";

Upvotes: -1

Related Questions