For example, I have the following code :
$string = "adf gggg eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.
I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value
, no luck so far though.
Thanks for any help.
.*
is greedy, so it will match as many characters as possible, you want .*?
which will match the minimum characters needed to complete the match:
/(value).*?(\(\d+\))/
What's wrong with your regex is that .* is greedy, and tries to matchs as many letters as possible.
preg_match("#value.*?\((\d+)\)#is", $string, $result);
But you can make it faster by using a negative class:
preg_match("#value[^(]+\((\d+)\)#is", $string, $result);
.*?value.*?\((\d+)\).*
Being *? a reluctant match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.