1,105,225 Community Members

finding string in file

Member Avatar
SPeed_FANat1c
Posting Pro
514 posts since Apr 2010
Reputation Points: 3 [?]
Q&As Helped to Solve: 18 [?]
Skill Endorsements: 0 [?]
 
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?

Member Avatar
Insensus
Junior Poster
112 posts since Mar 2011
Reputation Points: 52 [?]
Q&As Helped to Solve: 46 [?]
Skill Endorsements: 0 [?]
 
0
 

You've misplaced the parenthesis in this line:

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

Should of course be:

if(strcmp($line,$name) == 0) {
Member Avatar
kokoro90
Light Poster
26 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 10 [?]
Skill Endorsements: 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().

Member Avatar
SPeed_FANat1c
Posting Pro
514 posts since Apr 2010
Reputation Points: 3 [?]
Q&As Helped to Solve: 18 [?]
Skill Endorsements: 0 [?]
 
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 2 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: