Suppose i have a string:
$s= "The quick brown fox jumps over the lazy dog"
I want to use php regex 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
by
$1:Quick test:
If you want the second, fourth, etc. words retained, then you can adapt the regex to
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:
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:
Demo:
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$1and not$2.