PHP: search in a text file after certain phrases / words and output

I am trying to make a small PHP script to automate some workflows. What the script needs to do is read the file (approximately 10-20 kb per file). Then I need to find a file for some specific phrases and output - if phrases appear - linenumber number and phrase.

For example, Ive text file Im reading and searching inside. I'm looking for the phrases "Flower yellow", "White horse", "Mixed",

Then my conclusion:

Line 4: “White horse” Line 19: “Mixed”; Line 22: "Mixed"; Line 99: "Flower Yellow" ... etc.

Im using this code that correctly displays each line and line number, but I just can't perform a search procedure that only displays the phrases found:

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

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

I had to use strpos , and then every time I find the phrase to appear, it puts it in an array (or a dictionary), which has a row number as a key and a phrase as a value, but didn’t have the ability to make it work, and I thought, what could be the best and most effective method.

Any help or suggestions in which direction Ive to go would be greatly appreciated.

Thank you
- Mestika

+3
source share
3 answers
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 );
+2
source

Create a script that will insert your data and output the results to your PHP script.

+1

: -

0

All Articles