finding string in file
Hi,
I don't get why my funcion finds the string even if it doesn't exist in textfile:
function name_exists($name) {
$f = fopen($this->path, "r");
//echo $this->path;
while ( $line = fgets($f) ) {
if(strcmp($line,$name == 0)) {
echo 'exists';
fclose($f);
return TRUE; //we found it and can stop the function
}
}
fclose($f);
return FALSE;
}
Can you help me?
38 Minutes
Discussion Span
SPeed_FANat1c
Posting Pro in Training
482 posts since Apr 2010
Reputation Points: 13
Solved Threads: 17
Skill Endorsements: 0
You've misplaced the parenthesis in this line:
if(strcmp($line,$name == 0)) {
Should of course be:
if(strcmp($line,$name) == 0) {
Insensus
Junior Poster
112 posts since Mar 2011
Reputation Points: 70
Solved Threads: 46
Skill Endorsements: 0
Another consideration is that you are matching the entire line, so it compares $name against the entire line you are processing in each iteration instead of doing a pattern match. For just matching $name somewhere in $line you should use preg_match().
kokoro90
Light Poster
26 posts since Feb 2009
Reputation Points: 10
Solved Threads: 10
Skill Endorsements: 0
thank you. I made this and it works:
function name_exists($name) {
$f = fopen($this->path, "r");
while ( $line = fgets($f) ) {
$arr = explode( "\n", $line ); //remove linebreak before comparing
if(strcmp($arr[0],$name) == 0) {
fclose($f);
return TRUE; //we found it and can stop the function
}
}
fclose($f);
return FALSE;
}
SPeed_FANat1c
Posting Pro in Training
482 posts since Apr 2010
Reputation Points: 13
Solved Threads: 17
Skill Endorsements: 0
Question Answered as of 2 Years Ago by
kokoro90
and
Insensus