php - preg_match_all to find all words after a certain string

757

I have the following string:cache:search:amsterdam:hotel

I want to have apreg_match_all to find the wordsamsterdam andhotel (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 valuesamsterdam andhotel, 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 thecache:search?

287

Answer

Solution:

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

425

Answer

Solution:

Additionally to guys answers, in case you find it useful you can also use a regex like this:

(\w+):(\w+)$

Regex demo

preg_match_all('~(\w+):(\w+)$~', "cache:search:amsterdam:hotel", $matches);
435

Answer

Solution:

You can just collect the last two words. This should work:

preg_match_all( "/(\w+):(\w+)$/i", "cache:search:amsterdam:hotel", $matches )

Edit:

In case there are more than two words you want to capture I would recommendexplode instead:

$str = 'cache:search:amsterdam:hotel';
$matches = explode(':', substr($str, 13));
808

Answer

Solution:

A way to do this without a preg_match is this:

$matches = array_splice( ( explode( ':', 'cache:search:amsterdam:hotel' ) ), 2 );

I compared this to the accepted answer (the preg_match_all), that takes 56% longer to execute. The question was a regexp, so that will remain the accepted answer, but I wanted to post this alternative as well for people that come across the same problem

People are also looking for solutions to the problem: why does <?php echo date("m/d/Y" strtotime('second wednesday June 2016')) ?> output 6/15/2016 instead of 6/8/2016?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.