想想我有一个包含以下内容的文本文件:
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.
如何使用PHP找到所有“Jack”单词及其后面的单词?
所以结果将是
Jack Jordon
Jack Marais
Jack van
Jack
是否可以使用正则表达式执行此操作,还是有更好的方法?
答案 0 :(得分:2)
您可以在preg_match_all
中使用此正则表达式:
'/\bJack\s+(?:\s+\w+|$)/'
此正则表达式只会在Jack
或行结束后找到一个单词。
答案 1 :(得分:2)
您可以使用:
preg_match_all('~\bJack(?>\s+[a-z]+)?~i', $input, $matches);
print_r($matches[0]);
答案 2 :(得分:1)
试试:
$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);
答案 3 :(得分:1)
试试这个:
$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];
}
}
这将回应每个杰克+下一个词。