2

I meet a strange thing with the PHP function strpos(). I have a function that check if a passed string is found in a txt file. I can display the content of the file line by line but the strpos() doesn't return a value (nothing in fact). var_dump() of the return empty.

Can someone see a mistake, because I am lost. Thank you in advance.

My function :

function checkIfExist($string)
{
    $path = "\\\\server\\temp\\test.txt";
    $file = file($path);
    foreach( $file as $line )
    {   
       echo $line; //display the string in this line
       $found = strpos($file,$string);
       echo $found; //display nothing, not even a boolean/int 
}
return $found;
}
Ben
  • 31
  • 2
  • It looks like you're looking for the string in the entire contents of the file rather than in each line. Depending on the contents of `$string` and the file you may not be getting a match. – Dave Mar 05 '19 at 15:51

5 Answers5

1

Try to change $found = strpos($file,$string); to $found = strpos($line,$string);

Bart
  • 1,268
  • 2
  • 12
  • 14
1

Echoing a false boolean won't show up. Try changing it to a var_dump and you will see that it's a boolean set to false.

Dirk Scholten
  • 1,013
  • 10
  • 19
0

Sorry, I have made a mistake when writen the code, this is the good one :

function checkIfExist($string)
{
    $path = "\\\\server\\temp\\test.txt";
    $file = file($path);
    foreach( $file as $line )
    {   
       echo $line; //display the string in this line
       $found = strpos($line,$string);
       echo $found; //display nothing, not even a boolean/int
       var_dump($found); //display boolena(false) for all the test even if the 
                         string is well present once.


}
    return $found;
}
Ben
  • 31
  • 2
0

This code give the same result

foreach( $file as $line )
{   
    echo $line; //display "www.google.be"
    echo $string; //also display "www.google.be"
    //but when I then if the line contain the string, the function doesn't find 
      it!!!
    $pos = stripos($line,$hostname);
    var_dump($pos); // FALSE for all the test
}

I have done this thes in other code, and I never had this issue.

Ben
  • 31
  • 2
0

Setup debugging, so you see the values of strpos. If debugging cannot be arranged than vardump $line and $string. You will probably get unexpected values. Also try avoiding typecasting-issues. Perhaps this will work better.

if (strpos($line,$string) != false){...}else{...}