在文本文件中查找特定单词


Find specific word in text file

认为我有一个包含以下内容的文本文件:

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 Jordon
Jack Marais
Jack van
Jack

是否可以使用正则表达式执行此操作,或者有更好的方法?

您可以在

preg_match_all中使用此正则表达式:

'/'bJack's+(?:'s+'w+|$)/'

此正则表达式只会在行尾Jack OR 后面找到一个单词。

你可以使用这个:

preg_match_all('~'bJack(?>'s+[a-z]+)?~i', $input, $matches);
print_r($matches[0]);

试试:

$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);

试试这个:

$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];
    }
}

这将回显每个杰克 + 下一个单词。