Forum Moderators: coopster

Message Too Old, No Replies

preg match vs strpos

         

miketurpin

9:30 pm on Jan 15, 2011 (gmt 0)

10+ Year Member



An old 2005 post asked if it was possible to do:

preg_match('/^widget 2\.0/i', $string)

With strpos, and the conclusion was no.

Surely, you could use:

strpos($string, 'widget 2.0') == 0

This gives a starting anchor. To do an end anchor you'd also have to use strlen($string).

Note: to be exactly the same as the posted example, you'd have to use stripos to be insensitive of case.

miketurpin

9:34 pm on Jan 15, 2011 (gmt 0)

10+ Year Member



Whoops - I just realised that you actually need triple-equals:

strpos($string, 'widget 2.0') === 0

With double-equals, you'd get true even when 'widget 2.0' appears nowhere in the string.

brotherhood of LAN

10:40 pm on Jan 15, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to the forums miketurpin,

Well noted regarding the operators, as per the manual [php.net]

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.


So !== FALSE would return a match, even if the match starts at character '0'.

strpos is probably preferred to preg_match as it is faster. You could also use substr() since you know the string you're after and where it appears in your chosen text to search.