phpstrposword-boundary

Ensure whole word/number is matched while using strpos() to search for a substring


I'm facing problem while using strpos(). Let's say the string is "51 Minutes" and I'm checking for "1 Minute" it still returns true as it should not. What is the fix? I want to search only for 1 Minute.

Code :

if (strpos($str, '1 minute') !== false)
{

}

Solution

  • you are misunderstanding the usage of strpos

    strpos() returns either false, in the event that the string isnt found, or the numeric position of the first occurrence of the string being looked for. It does not return 'true'.

    To get a boolean result, you can test for not false like this. (notice the use of !== which tries to match value and type. This avoids 0 giving you a false result).

    if(strpos($haystack, $needle) !== false) {
        // do something here
    }
    

    Also note, that for some annoying reason the 'haystack' and 'needle' are the reverse of many of the other PHP string functions, which makes it easy to make a mistake.

    However, as you are trying to find a certain string, and only that certain string, you need to use either a straight comparison, like:

    if($string == '1 Minute')
    

    or use regex to match a complete word with a pattern such as this:

    $pattern = '/\b1 Minute\b/';
    

    this can then be used with preg_match like this:

    preg_match($pattern, $input_line, $output_array);
    

    If youve not used regex before, this site is very good for helping you create your patterns and even gives you the code line to paste in.