搜索包含字符串的字符串和返回行

时间:2015-05-13 07:10:35

标签: php search

我必须使用php创建网站,该网站可以搜索单词并返回包含已修复的3个输入文本中的单词的行。我能够搜索一个单词并检查它是否存在于输入文本中。如何搜索输出并返回包含单词

的行

这里是输入文件中的一些数据

<paragraph><Date><Date>TUESDAY</Date></Date>. <Date>MARCH 3, 1903</Date>
Outstation Prosperity.
</paragraph>
<paragraph>THE perusal of the various Annual Reports from Outstations is interesting: and very minutely shows the work of the Country.
</paragraph>

这是我编写的代码

<?php
$path = 'D:\Collective Intelligence\assignment&project\PROJECT-DATASET';
$findThisString = $_POST['search1'];

$dir = dir($path);

// Get next file/dir name in directory
while (false !== ($file = $dir->read()))
{   
    if ($file != '.' && $file != '..')
    {
        // Is this entry a file or directory?
        if (is_file($path . '/' . $file))
        {
            // Its a file, yay! Lets get the file's contents
            $data = file_get_contents($path . '/' . $file);

            // Is the str in the data (case-insensitive search)
            if (stripos($data, $findThisString) !== false)
            {
                // sw00t! we have a match
            echo 'match found in ' . $file . "<br>\n";

            }
        }
    }
}

$dir->close();

?>

1 个答案:

答案 0 :(得分:0)

您可以使用fgets查看您想要的那些行。只需添加一个简单的计数器:

if (is_file($path . '/' . $file)) {
    // Its a file, yay! Lets get the file's contents
    $data = file_get_contents($path . '/' . $file);

    $fh = fopen($path . '/' . $file, 'r');
    $i = 1;
    while(!feof($fh)) {
        $line = fgets($fh);
        if(stripos($line, $findThisString) !== false) {
            echo "match {$findThisString} found in line {$i}<br/>\n";
        }
        $i++;
    }
    fclose($fh);
}