Jump to content


Photo

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


  • Please log in to reply
3 replies to this topic

#1 vidyashankara

vidyashankara
  • Members
  • PipPipPip
  • Advanced Member
  • 75 posts

Posted 16 June 2006 - 10:43 PM

Lets say i have a text file like below

MODEL 1
abcd
efgh
1234
6789

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.

#2 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 16 June 2006 - 10:47 PM

$file = fread("file.txt");
$key = search_array ("1234", $file); // key representing the line..

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

#3 AndyB

AndyB
  • Staff Alumni
  • Advanced Member
  • 5,465 posts
  • LocationToronto

Posted 16 June 2006 - 10:48 PM

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.
Legend has it that reading the manual never killed anyone.
My site

#4 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 16 June 2006 - 10:50 PM

[!--quoteo(post=384800:date=Jun 16 2006, 11:48 PM:name=AndyB)--][div class=\'quotetop\']QUOTE(AndyB @ Jun 16 2006, 11:48 PM) View Post[/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;
}
z..z..z..z..z..z..z..z..




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users