Liam Bailey
Liam Bailey

Reputation: 5905

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

Upvotes: 1

Views: 1424

Answers (5)

Joony
Joony

Reputation: 4718

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

Upvotes: 0

Gordon
Gordon

Reputation: 317197

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.

Upvotes: 4

gnarf
gnarf

Reputation: 106412

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

Upvotes: 6

user268396
user268396

Reputation: 12006

If you are simply looking for a substring, stripos() or strpos() and friends are much better than using the preg family of functions.

Upvotes: 2

GordonM
GordonM

Reputation: 31780

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.

Upvotes: 1

Related Questions