What is the best way to search for a word in a string
preg_match("/word/",$string)
stripos("word",$string)
Or is there a better way
What is the best way to search for a word in a string
preg_match("/word/",$string)
stripos("word",$string)
Or is there a better way
One benefit to using regexp for this job is the ability to use \b (Regexp word boundary) in the regexp, and other random derivations. If you are only looking for that sequence of letters in a string stripos is likely to be a little better.
$tests = array("word", "worded", "This also has the word.", "Words are not the same", "Word capitalized should match");
foreach ($tests as $string)
{
echo "Testing \"$string\": Regexp:";
echo preg_match("/\bword\b/i", $string) ? "Matched" : "Failed";
echo " stripos:";
echo stripos("word", $string) >= 0 ? "Matched": "Failed";
echo "\n";
}
Results:
Testing "word": Regexp:Matched stripos:Matched
Testing "worded": Regexp:Failed stripos:Matched
Testing "This also has the word.": Regexp:Matched stripos:Matched
Testing "Words are not the same": Regexp:Failed stripos:Matched
Testing "Word capitalized should match": Regexp:Matched stripos:Matched
- and a letter would match for \b -- so \bwork would match co-worker -- You can get more specific with lookahead and lookbehindLike it says in the Notes for preg_match:
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
stristr or stripos if you need case-insensitive.stripos does not return FALSE, it means the searched word is within the string, so it is very much appropriate to use stripos for finding out if the word exists within another string (unless you need boundaries). And as I quoted from the PHP Manual, it is also faster than using preg_match. You are basically saying, the PHP manual is wrong. If you really think that, please go to the linked manual page and click the Report A Bug Link and tell them.For simple string matching the PHP string functions offer more performance. Regex is more heavyweight and therefore has lower performance.
Having said that, in most cases, the performance difference is small enough to go unnoticed, unless you're looping over an array with hundreds of thousands of elements or more.
Of course, as soon as you start needing "cleverer" matching, regex becomes the only game in town.
There is also substr_count($haystack, $needle) which just returns the number of substring occurences. With the added bonus of not having to worry about 0 equating to false like stripos() if the first occurrence is at position 0. Although that's not a problem if you use strict equality.