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;
}
Try to change $found = strpos($file,$string);
to $found = strpos($line,$string);
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
.
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;
}
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.
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{...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.