Jump to content

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


vidyashankara

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.
Link to comment
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;
}
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.