Jump to content

Recommended Posts

Is it possible to get a line of a string from a text file?

A function that would open a text file, search for a specified string and if it is found, it would ge the line where the string is located in text file.

 

If my text file was something like this:

Line1
Line2
Line3
Line4

If I was finding a line of the string "Line3", function would return as "3".

The file() function returns the contents of a file in an array by line. So..

 

<?php
$myfile=file("/path/to/file.txt");
$linecount=0;
foreach($myfile as $myline){
   $linecount++;
   if($myline=="searchstring"){//just an example, use what ever search method fits
      echo $linecount;
   }
}
?>

 

OR maybe

 

<?php
$myfile=file("/path/to/file.txt");
foreach($myfile as $key=>$myline){
   if($myline=="searchstring"){//just an example, use what ever search method fits
      echo ($key+1);
   }
}
?>

 

I did not test either of these, but should be a start, if I am understanding you anyway.

i was beat to the answer, but here's my version...

 

$test_string = "somestring";
$c_array = file("./yourfile.txt");
$c_size = count($c_array);

for ($i=0; $i<$c_size;$i++) {
    if (trim($c_array[$i]) == $test_string) {
       echo "$test_string was found on line ".($i + 1);
    }
}

I was only trying to illustrate reading the file and returning the line, the search method can be nearly anything.

$myline=="texttofind" - would attempt to match the entire line

strstr("texttofind",$myline) - would find the first occurance of "texttofind"

preg_match("/texttofind/",$myline) - uses regular expression to match any text (or pattern) in line

 

I suspect strstr() may be the best option for you.

http://us2.php.net/manual/en/function.strstr.php

It will work just as well, to do strstr("3",$myline)

It would then find the first "3" on a line.

 

Guys! Guys!! :D

 

<?php function getstrline($searchstr, $file){
  $c_array = file($file);
  $c_size = count($c_array);

  for ($i=0; $i < $c_size; $i++){
    if(strpos(Trim($c_array[$i]), $searchstr))
   	return $i;
  }
} ?>

 

Can someone tell me whats wrong with that? It will return 0 in the loop, but I tried like this:

<?php function getstrline($searchstr, $file){
  $c_array = file($file);
  $c_size = count($c_array);

  return strpos(Trim($c_array[0]), $searchstr)
} ?>

It worked like that. When I wrote the first word or part of word of the text file on $searchstr.

 

Please, can someone tell me whats wrong with the loop, if the loop worked then this whole thing would work, i copied it from BlueSkyIS and changed it to check strpos.

There is already a built in function to open a file and return everything as an array.  There is already a built in array search function.

 

  $file = file("the/file");
  $key = array_search($search, $file);
  if($key === FALSE){
    echo "Not found";
  }

 

If you want all matching lines, use the array_keys() function.

There is already a built in function to open a file and return everything as an array.  There is already a built in array search function.

 

  $file = file("the/file");
  $key = array_search($search, $file);
  if($key === FALSE){
    echo "Not found";
  }

 

If you want all matching lines, use the array_keys() function.

I dont quite understand how to use that, or where I need that, but the first problem is now:

1. The function doesnt work that I posted above, strpos will return true ( > 0 ) without loop, but it wont return when its in the loop. I would like to have that fixed/told why it wont work.

The code I gave you IS the function body.  Just make it return $key and you're done.  You don't need to loop or perform any comparisons yourself; there are already built in functions to handle this stuff.  Why re-invent the wheel?

My deepest apologies roopurt18... I did not know of that function.

 

That will work as long as the matching method used by array_search() is the way he wants to match.

 

<?php
function getstrline($searchstr, $file){
   $myfile=file($file);
   $key=array_search($searchstr,$myfile);
   return ($key+1);
}
?>

 

How about that, Pentti?

 

... one reason to loop through the array yourself would be if you want to use regex to make your match. Unless I am missing something with array_search(), it does not appear to support regex.

My deepest apologies roopurt18... I did not know of that function.

 

That will work as long as the matching method used by array_search() is the way he wants to match.

 

<?php
function getstrline($searchstr, $file){
   $myfile=file($file);
   $key=array_search($searchstr,$myfile);
   return ($key+1);
}
?>

 

How about that, Pentti?

 

... one reason to loop through the array yourself would be if you want to use regex to make your match. Unless I am missing something with array_search(), it does not appear to support regex.

Thanks, but somethings wrong with array_search.

It will only return the line where word is if I search for the word thats the last word in the text file!

 

Test it yourself!

php code:

<?php
function getstrline($searchstr, $file){
  $myfile = file($file);
  $key = array_search($searchstr, $myfile);
  return ("'$searchstr' at line: $key");
}

Echo getstrline("Line4", "test.txt");
?>

 

text file:

Line0
Line1
Line2
Line3
Line4

 

result when finding "Line4":

'Line4' at line: 4

 

result when finding "Line3" (or lower):

'Line3' at line:

Thanks for the help guys! But I attempted to make a working function, to work just like I wanted it to work.

If anyone wants to see the function, here it is:

 

<?php
function getstrline($searchstr, $file){
  $c_array = file($file);
  $c_size = count($c_array);

  $i = 0;
  while($i <= $c_size - 1){
    if(strpos(Trim($c_array[$i]), $searchstr))
    return $i;
    $i++;
  }
}
?>

You might want the function to return FALSE or -1 as the last line of the function for cases where the search string is not found.

 

Also, instead of calling count() and using a while loop, you could use a foreach loop, which is intended for looping over arrays.

 

This is a very, very minor optimization note, but you can apply the concept to other areas of your code.

while($i <= $c_size - 1){

That is perfectly fine for your while loop, but you are forcing the interpreter to re-evaluate the expression $c_size - 1 each time through the loop.  So let's say the file was 1000 lines long, the expression $c_size - 1 will be calculated 1000 times; however, it's always going to be the same result.  This means we can move the calculation outside the loop so that it is only ever calculated once:

$c_size--;
while($i <= $c_size){

You can eliminate the -1 operation altogether by changing the comparison in the while loop as well:

while($i < $c_size){

Like I started off by saying, that is a very minor optimization and barely worth performing; it's only going to shave maybe a millisecond off your execution time, if that.  However, if the $c_size - 1 had been a different, more expensive (expensive in terms of computation time) operation, such as a function call, it's a good optimization to make.

 

Lastly:

    if(strpos(Trim($c_array[$i]), $searchstr))
    return $i;

That code is perfectly legal, but I highly recommend always, always, always placing curly brackets around the bodies of your conditional statements and loops, even when they're a single line and optional.  The reason for this is its very easy to add another line to the body of a conditional or loop to enhance functionality or for debugging purposes but then forget to add the curly brackets, which breaks the loop / conditional.  It only takes an extra second to type the keystrokes and sure it adds one more line to your source file, but honestly it can save you a good half hour or more of frustration down the road.

  if(strpos(trim($c_array[$i]), $searchstr)){
    return $i
  }

You should also always indent the bodies of your conditionals and loops as well, to enhance readability.

 

I only bring this stuff up now because you are learning so its easier to develop good habits now rather than break bad habits later.  When I was learning to program, my sources (books / professors) said the same things and you just have to take it on faith.  I decided to listen and I can't tell you how many times throughout college I saw people have trouble debugging or fixing their code because they didn't do little things like that.

 

Best of luck to you.

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.