Question

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 linenumber(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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top