Jump to content

match a line in .txt file


mraza

Recommended Posts

Hi

I need to read a file and if a line match then proceed, file have content like this

 

file.txt

this is line one
this line two
and this line three

 

my code:

$content = file_get_contents("file.txt");
if (strstr("this line two", $content)) {
echo 'matched';
} else {
echo 'not matched';
}

but this always give not matched. any help plz

 

Link to comment
https://forums.phpfreaks.com/topic/217678-match-a-line-in-txt-file/
Share on other sites

you could read the file into an array and loop over the elements of that array, looking for matches:

 

$content = file('file.txt');
foreach ($content AS $aline) {
    if (strstr("this line two", $aline)) {
        echo 'matched';
    } else {
        echo 'not matched';
    }
}

thanks for help , but that did not worked either, when i did a print_r($content) this what i get

Array ( [0] => this is line one this line two and this line three )

 

so all three lines it put in one array element, then i even tried

$c = explode("\r\n", $content);

 

but again it shows me above results.

thanks

 

here is exactly file.txt

this is line one
this line two
and this line three

 

and this mycode.php

<?php
$content = file('file.txt');
// i tried like this too
$c = explode("\r\n",$content);
print_r($content);
foreach ($content AS $aline) {
    if (strstr("this line two", $aline)) {
        echo 'matched';
    } else {
        echo 'not matched';
    }
}
/*
// Result with  print_r($content)
Array ( [0] => this is line one this line two and this line three ) not matched

// Result with  print_r($c)
Array ( [0] => Array ) not matched
*/

?>

ok this works

$content = file_get_contents('file.txt');
$content = explode("\r\n",$content);
print_r($content);
foreach ($content AS $aline) {
    if (strstr($aline, " this is line three")) {
        echo 'matched';
    } else {
        echo ' not matched';
    }
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.