patrick patrick - 6 months ago 24
PHP Question

preg_match_all to find all words after a certain string

I have the following string:

cache:search:amsterdam:hotel


I want to have a
preg_match_all
to find the words
amsterdam
and
hotel
(in this case). I've done some looking around and came to:

preg_match_all( "/(?<=cache:search)(:/w*)/i", "cache:search:amsterdam:hotel", $matches )


I'm hoping to get $matches to have the values
amsterdam
and
hotel
, but so far I was only able to get
:amsterdam:hotel
or just
:amsterdam
in various tries. How can I get all words in between the parenthesis after the
cache:search
?

Answer

First, once you have extracted :amsterdam:hotel you can easily split the string.

If you want to directly obtain separated words, you can use a \G based pattern:

preg_match_all('~(?:\G(?!\A)|cache:search):\K[^:]+~', $subject, $matches);

Where \G matches the position immediately after the previous match. (Note that \G matches the start of the string too, that's why I added (?!\A).)