开发者

PHP: Search in textfile after specific phrases / words and output

I’m trying to make a small php script to automate some work processes. What the script has to do is read a file (approximately 10-20kb per file). Then I need to search the file for some specific phrases and output – if the phrases occur – the li开发者_如何学Cnenumber(s) and the phrase.

For example, I’ve a text-file I’m reading and searching within. I search for the phrases “The flower is yellow”, “The horse is white”, and “mixed;”

Then my output is:

Line 4: “The horse is white” Line 19: “Mixed;” Line 22: “Mixed;” Line 99: “The flower is yellow” … and so on.

I’m using this code, which correctly output each line and the line number but I just can’t make a search routine that only output the searched phrases:

<?php
$lines = file('my-text-file.txt');

foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
?>  

My though was to use strpos and then every time I find an occurrence of the phrase it put it into an array (or dictionary) which the line number as key and the phrase as value but haven’t been able to make it work and I thought that there might be a better and more effective method.

Any help or suggestions in which direction I’ve to go would be very much appreciated.

Thanks

- Mestika


function search ( $what = array (), $filePath ) {
    $lines = file ( $filePath );

    foreach ( $lines as $num => $line ) {
        foreach ( $what as $needle ) {
            $pos = strripos ( $line, $needle );
            if ( $pos !== false ) {
                echo "Line #<b>{$num}</b> : " . htmlspecialchars($line) . "<br />\n";
            }
        }
    }
}

#   Usage:
$what = array ( 'The horse is white', 'The flower is yellow', 'mixed' );
search ( $what );


Create a script that will grep your input and pipe the results into your PHP script.


Vide this: Find a string in a text file and add something to that line

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜