如何使用PHP在文本文件中搜索字符串

问题描述 投票:0回答:1

我有一个PHP代码读取TEXT文件并显示其内容。

我希望允许用户搜索他想要的任何单词,如果可用,系统将使用行号显示它。

直到现在我能够阅读文本并显示它。

我知道我需要逐行阅读并存储在变量中,或者有更好的选择吗?

code

<?php


    $myFile = "test.txt";

    $myFileLink = fopen($myFile, 'r');

    $myFileContents = fread($myFileLink, filesize($myFile));

    while(!feof($myFileContents)) { 
            echo fgets($myFileContents) . "<br />";
        }

    if(isset($_POST["search"]))
    {
        $search =$_POST['name'];
        $myFileContents = str_replace(["\r\n","\r"], "\n",  $myFileContents);
        if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE))
        {
            foreach($matches[1] as $match)
            {
            $line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
            echo "Found $search on $line";
            }
        }
    }


    fclose($myFileLink);

    //echo $myFileContents; 
    ?>

    <html>
        <head>

        </head>
        <body>
         <form action="index.php" method="post">
              <p>enter your string <input type ="text"  id = "idName"  name="name" /></p>
              <p><input type ="Submit" name ="search" value= "Search" /></p>
        </form>
        </body>
    </html>
php loops readfile line-by-line
1个回答
1
投票

像这样的东西

$myFileContents = file_get_contents($myFileLink);

if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
    print_r($matches);
}

使用Preg匹配all和不区分大小写的标志。

获取行号要困难得多,因为您需要执行以下操作:

$myFileContents = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.";

$search = "non proident";

//normalize line endings.
$myFileContents = str_replace(["\r\n","\r"], "\n",  $myFileContents);

    //Enter your code here, enjoy!
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE)){

    foreach($matches[1] as $match){
        $line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
        echo "Found $search on $line";
    }

}

输出

Found non proident on 5

你可以看到它live here

如果它是一个大文件,你可以在阅读每一行时进行类似的搜索。像这样的东西

 $myFileLink = fopen($myFile, 'r');

 $line = 1; 

 while(!feof($myFileLink)) { 
     $myFileContents = fgets($myFileLink);
     if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
        foreach($matches[1] as $match){
           echo "Found $match on $line";
        }
     }
     ++$line;
 }
© www.soinside.com 2019 - 2024. All rights reserved.