Check for word in string
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
Like 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.
If you are simply looking for a substring, stripos()
or strpos()
and friends are much better than using the preg
family of functions.
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.
http://php.net/manual/en/function.substr-count.php
精彩评论