在文本文件中查找特定单词[关闭]

在文本文件中查找特定单词[关闭]

问题描述:

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?

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

  你好,我叫Jack Jordon。 你叫什么名字? 让我们举办派对。 你叫Jack Marais,我不是这么认为Jack van Riebeeck。 美好的一天杰克。
  code>  pre> 
 
 

如何用PHP找到所有“杰克”字样及其后面的字? p>

所以结果将是 p>

  Jack Jordon 
Jack Marais 
Jack van 
Jack 
  code>  pre> 
 
 

是否可以 使用正则表达式执行此操作还是有更好的方法? p> div>

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