Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP代码,用于在文本文件中搜索单词并显示内容_Php_Design Patterns_Matching - Fatal编程技术网

PHP代码,用于在文本文件中搜索单词并显示内容

PHP代码,用于在文本文件中搜索单词并显示内容,php,design-patterns,matching,Php,Design Patterns,Matching,sam.php tp.txt: 战场3非常好,这说明了很多。 这一系列的游戏是迄今为止最好的。 战场4是迄今为止最好的战场。 处理它的最好方法就是解决它。 你在早期就注意到了这一点,这很好。 他太棒了 tp2.txt: 好 最好的 问题: 我想从tp.txt文件中搜索所有出现的单词good和best,并显示包含这些单词的相关行。在输出中,它给出tp.txt中的所有行,无论是否找到匹配项。 请向任何人提供帮助。尝试以下代码: <?php $file = "tp2.txt"; $fh1 =

sam.php

tp.txt:

战场3非常好,这说明了很多。 这一系列的游戏是迄今为止最好的。 战场4是迄今为止最好的战场。 处理它的最好方法就是解决它。 你在早期就注意到了这一点,这很好。 他太棒了

tp2.txt:

好 最好的

问题: 我想从tp.txt文件中搜索所有出现的单词good和best,并显示包含这些单词的相关行。在输出中,它给出tp.txt中的所有行,无论是否找到匹配项。 请向任何人提供帮助。

尝试以下代码:

<?php

$file = "tp2.txt";
$fh1 = fopen($file, "r") or die("File ($file) does not exist!");
$fh2 = fopen("tp.txt", "r") or die("File ($file) does not exist!");
$fh3 = fopen("tp3.txt", "w") or die("File ($file) does not exist!");
$members=array();
$tags=array();
$i = 0;
while (!feof($fh1))
{
$members[] = fgets($fh1);
}
while (!feof($fh2))
{
$tags[] = fgets($fh2);
}
    for($i=0;$i<sizeof($members);$i++)
    {
        $chk=$members[$i];
        //echo $chk;

        //fwrite($fh3,$members[$i]);
        for($j=0;$j<sizeof($tags);$j++)
        {
            $n = preg_quote($chk);

            if (preg_match_all("/\b$n\b/", $tags[$j]))
            //if (preg_match('/'."\b$chk\b".'/', $tags[$j]))
            {

                fwrite($fh3,$tags[$j]);
            }
        }
        //if(in_array($chk,$tags))echo "success";


    }


fclose($fh1);
fclose($fh2);
fclose($fh3);
?>

但是我希望每一行都写在文本文件tp3.txt中的新行上……那么在文件put\u contents???文件put\u contents'tp3.txt',$string中我该怎么做呢。PHP\u EOL,文件\u追加;或者从$text初始化代码中删除文件\u忽略\u新行标志。
$text = file('tp.txt', FILE_SKIP_EMPTY_LINES);
$words = file('tp2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$pattern = implode('|', $words);

foreach ($text as $string) {
    if (1 === preg_match("/(?:$pattern)/", $string))
        file_put_contents('tp3.txt', $string, FILE_APPEND);
}