1.11M Members

finding string in file

 
0
 

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?

 
0
 

You've misplaced the parenthesis in this line:

if(strcmp($line,$name == 0)) {

Should of course be:

if(strcmp($line,$name) == 0) {
 
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().

 
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;
		
	}
Question Answered as of 3 Years Ago by kokoro90 and Insensus
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: