Jump to content

Archived

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

vidyashankara

Locate a string in a text file, return the line number.

Recommended Posts

Lets say i have a text file like below

[code]
MODEL 1
abcd
efgh
1234
6789
[/code]

Is there a script which can tell me which line can i find "1234" in?

ie, the string should output "1234 is in line 4." in this case. how do i do that? strpos doesnt seem to work, it returns the str position, not the line number.

Share this post


Link to post
Share on other sites
$file = fread("file.txt");
$key = search_array ("1234", $file); // key representing the line..

that'll only get it if the line is only "1234"

Share this post


Link to post
Share on other sites
Use the file() function to read the text file into an array (now you'll know which line is which) so you can echo the index value for lines which match your condition.

Share this post


Link to post
Share on other sites
[!--quoteo(post=384800:date=Jun 16 2006, 11:48 PM:name=AndyB)--][div class=\'quotetop\']QUOTE(AndyB @ Jun 16 2006, 11:48 PM) [snapback]384800[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Use the file() function to read the text file into an array (now you'll know which line is which) so you can echo the index value for lines which match your condition.
[/quote]
yes you're right my mistake...file not fread.

if you want to know what line it's in...
$file = file ("file.txt");
foreach ($file as $line => $text)
{
if (preg_match ("/1234/", $text)) $line_with_str = $line;
}

Share this post


Link to post
Share on other sites

×

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.