handmdmr
handmdmr

Reputation: 923

php regex vs strpos for accuracy

I have read through other posts comparing the two functions. strpos() and preg_match(). I understand that strpos() is the way to go if you know the exact string your looking for but what if the search subject occurs within the string.

$string = 'Honda 1974 1975 CB200 T Front ATK Wheel Hub w/ Brake Disc Rotor 18" x 1.60 Straight!';

I need to look for the CB200 and a bunch of other similar models such as CB1000, CR250, CR125 and so on.

If I used

preg_match('/^.*\b(c{1}b{1}2{1}0{1}0{1})\b.*$/i',$string)

I would get that exact string with nothing in front or behind it but strpos($string,'CB200') would find matches no matter what is in front or behind the searched subject.
Example: Honda FrontCB200ATK Wheel Hub. If that is a part number then then strpos() would fail. Can I make strpos() more accurate or would I need to use preg_match() in this situation? Giving up the speed of strpos(). The script will compare up to 10,000 $string's at each execution having multiple conditions to follow in each comparison.

Upvotes: 1

Views: 1657

Answers (2)

arezab
arezab

Reputation: 75

Because of the accuracy of preg_match() I tend to use preg_match specially for form validation.

Upvotes: 0

hwnd
hwnd

Reputation: 70750

Everyone has a different opinion on something, and the best method for comparing is one of those things.

I would most likely prefer to use strpos() over preg_match() because regular expressions are generally more expensive. Both of these functions are quick, but if you are worried about performance then you should use strpos() to test for a string in this case.

The documentation for preg_match() clearly states:

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 wanting to use preg_match() I would rewrite your expression to something like the following.

preg_match('/\b(?:cb[12]000?|cr[12][25][50])\b/i', $string);

Upvotes: 1

Related Questions