简体   繁体   中英

php strpos() not checking correctly

I'm facing problem while using strpo(). 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)
{

}

Thanks!

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.

Use preg_match() to find whole words.

The code you're looking for:

$string = "Lorem ipsum 51 Minutes on StackOverflow";
$regex = "/\b1 Minute\b/";    

$match = preg_match( $string, $regex );

Documentation: http://php.net/manual/en/function.preg-match.php

Since someone went the regex overkill route let me offer the simplest route. strpos returns the position of the string that matched, not just if it matched. So...

$str = "1 Minute here";
if(strpos($str, '1 Minute') === 0) {
    echo 'Matched 1 Minute';
}

If it's at position 0, then it means the string starts with 1 Minute . Assuming you don't want to do anything crazy like find all instances of the word, this can suffice. Otherwise, use the regex answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM