PHP Logo

PHP: Search for String in a String Using strpos

This is more for my own reference than anything else, working on a recent project where specific terms and stock numbers needed to be excluded, the below function quickly allowed me to action the excluded items to ensure their exclusion.

Its different to the other options out there because of the use of ‘!==’, there is an issue when using strpos, that is if finds the string at position 0, then it gives a false positive, where as using ‘===’ or ‘!==’ checks for ‘identical’ or ‘not identical; matches.

Possibly the most boring post yet :)

//Decalre Vars
$haystack 	= array (
				"123",
				"456",
				"789"
			);

if(CheckIfExists($item->Title)) {
	// Do something if its found
}
						
function CheckIfExists($needle)
{				
	global $haystack;
	
	foreach($haystack as $needles) {
		
		if (strpos($needle, $needles) !== false) {
			//echo "We have a banned Item!! - " . $needle;
			return true;
		}
	}
	return false;
}
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *