Reputation: 652
I have PHP app and I would like to get string "word" followed after another word. It can be followed by another strings.
I would like to always get the "ok" status. How to do that please?
I have:
preg_match('~status:\s(.*)(?=\s.*)?~', $text, $matches);
But is returns everything after status:.
Upvotes: 0
Views: 881
Reputation: 21975
You could do it using a positive-lookbehind and take every word character after it.
(?<=status:\s)(\\w+)
Upvotes: 2
Reputation: 521259
You could just replace (.*)
with (\w*)
:
preg_match('~status:\s(\w*)~', $text, $matches);
Another way to fix your current approach would be to make the dot in (.*)
lazy, and then also make a slight change to your current lookahead:
preg_match('~status:\s(.*?)(?=\s|$)~', $text, $matches);
Upvotes: 2
Reputation: 48711
You may ask why your current solution doesn't work?
If you see it matches a whitespace character after matching status:
then matches up to end of line by .*
then backtracks to find a match where a space exists. If a whitespace after ok
doesn't exist immediately or somewhere later in string no matches is found. Solution:
status:\s+\K\w+
You don't need capturing groups and shouldn't quantify a lookahead either.
See live demo here
PHP code:
preg_match('~status:\s+\K\w+~', $text, $matches);
Upvotes: 2