Think I have a text file with the following:
Hello my name is Jack Jordon. What is your name? Let there be a party. Is your name Jack Marais, I didn't think so Jack van Riebeeck. Good day Jack.
How can I find all the "Jack" words and the word after it with PHP?
So the results would be
Jack Jordon
Jack Marais
Jack van
Jack
Is it possible to do this with regex or is there a better way?
You can use this regex in preg_match_all
:
'/\bJack\s+(?:\s+\w+|$)/'
This regex will only find a single word after Jack
OR end of line.
Just try with:
$input = 'Hello my name is Jack Jordon. What is your name? Let there be a party. Is your name Jack Marais, I didn\'t think so Jack van Riebeeck. Good day Jack.';
$search = 'Jack';
preg_match_all('/(' . $search . '[a-z ]*[A-Z][a-z]+)/', $input, $matches);
$output = $matches[0];
var_dump($output);
try this :
$yourSentend = "Hello my name is Jack Jordon. What is your name? Let there be a party. Is your name Jack Marais, I didn't think so Jack van Riebeeck. Good day Jack.";
$words = explode(' ', $yourSentence);
for ($i = 0, $m = count($words); $i < $m; $i++) {
if ($words[$i] == 'Jack') {
echo $words[$i].' '.$words[$i+1];
}
}
This will echo each Jack + the next word.
You can use this:
preg_match_all('~\bJack(?>\s+[a-z]+)?~i', $input, $matches);
print_r($matches[0]);