MakoBuk
MakoBuk

Reputation: 652

Regex - word followed after another word

I have PHP app and I would like to get string "word" followed after another word. It can be followed by another strings.

  1. Hello, this is status: ok
  2. Hello, this is status: ok.
  3. Hello, this is status: ok and I like it.

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

Answers (3)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You could do it using a positive-lookbehind and take every word character after it.

(?<=status:\s)(\\w+)

Demo

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

You could just replace (.*) with (\w*):

preg_match('~status:\s(\w*)~', $text, $matches);

Demo

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

revo
revo

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

Related Questions