1

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.

1
  • Try .*\(\s*(-?[\d,]+)[\w\s]*\) Commented Sep 18, 2015 at 13:40

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Should your main capture group in the second example be ([+-]?\d+(?:,\d+) to account for negatives?
Sorry, was in a hurry. Fixed both.
-1

try this pattern :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.