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
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';
    }
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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
*/

?>

Link to comment
Share on other sites

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';
    }
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.