Suppose i have a string:
$s= "The quick brown fox jumps over the lazy dog"
I want to use php re开发者_开发百科gex functions to retrieve every alternate word from the sentence. Like for the above sentence, the output should be:
The brown jumps the dog
Can anyone help me with the REGEX for this?
You can replace every two words by the first one. So, replace
(\w+) \w+
by $1
:
preg_replace('/(\w+) \w+/', "$1", 'The quick brown fox jumps over the lazy dog')
Quick test:
php -r 'echo preg_replace("/(\w+) \w+/", "$1", "The quick brown fox jumps over the lazy dog");'
The brown jumps the dog
If you want the second, fourth, etc. words retained, then you can adapt the regex to
\w+ (\w+)
which will put the second word in a capture group. However. This will retain the very last word, even when the number of words is odd:
php -r "echo preg_replace('/\\w+ (\\w+)/', '\\1', 'The quick brown fox jumps over the lazy dog'),\"\\n\";"
quick fox over lazy dog
See that stray »dog« at the end? To solve that you need to remove the very last word if there isn't one following it:
\w+(?: (\w+))?
Demo:
php -r "echo preg_replace('/\\w+(?: (\\w+))?/', '\\1', 'The quick brown fox jumps over the lazy dog'),\"\\n\";"
quick fox over lazy
The (?:...)
part is a so-called non-capturing group. It will group parts of the regex without capturing its contents for backreferences. This is here mainly so you can still replace by $1
and not $2
.
Or, if you want to capture the matches in an array:
preg_match_all('/(?|(\w+) \w+|(\w+)$)/', $s, $matches);
var_dump($matches[1]);
And to grab the opposite positions:
preg_match_all('/\w+ (\w+)/', $s, $matches);
var_dump($matches[1]);
精彩评论