We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,621 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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?

3
Contributors
3
Replies
38 Minutes
Discussion Span
2 Years Ago
Last Updated
4
Views
Question
Answered
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

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0621 seconds using 2.72MB