how to check for text w/in string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

how to check for text w/in string

Post by someguyhere »

I have a chunk of text (an unordered list in this case) and I just want to check whether a certain bit of text is contained within it. I've look at a few tutorials but can't get it to return anything expect false. Any ideas?

Code: Select all

				$ldo = strpos($member_data['designation'], 'Certified LifeDocuments™ Organizer');
					if ($ldo === true){
						$lifedocuments = 'checked';
					}
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: how to check for text w/in string

Post by someguyhere »

Well, I don't know why, but it works fine after I trimmed the string to find down, as such:

Code: Select all

				$ldo = stristr($member_data['designation'], 'lifedocuments');
					if ($ldo == true){
						$lifedocuments = 'checked';
					}
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: how to check for text w/in string

Post by someguyhere »

FYI - in case anyone runs into this, it *seems* to be the difference of == vs. ===. With three, it compares the variable type, which may be what cause it to return false since one was an array and one was a string.

Or, I could be completely wrong.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: how to check for text w/in string

Post by McInfo »

The first code sample uses strpos() which returns an integer related to the position of the search string or FALSE if the search string could not be found. Therefore, no value returned by strpos() will ever be identical (===) to TRUE.

The second code sample uses stristr() which returns a string containing "all of haystack from the first occurrence of needle to the end" or FALSE if the search string was not found. Most strings are equal (==) to TRUE. Therefore, if the search string is found, $ldo might be equal to TRUE.

The correct way to do the search is to use strpos() or stripos(). If the return value is not identical (!==) to FALSE, the search string was found.
Post Reply