简体   繁体   English

php strpos() 没有正确检查

[英]php strpos() not checking correctly

I'm facing problem while using strpo().我在使用 strpo() 时遇到问题。 Let's say the string is "51 Minutes" and I'm checking for "1 Minute" it still returns true as it should not.假设字符串是“51 分钟”,我正在检查“1 分钟”它仍然返回 true,因为它不应该。 What is the fix ?什么是修复? I want to search only for 1 Minute.我只想搜索 1 分钟。

Code :代码 :

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

}

Thanks!谢谢!

you are misunderstanding the usage of strpos你误解了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. strpos()返回 false(如果未找到字符串)或正在查找的字符串第一次出现的数字位置。 It does not return 'true'.它不会返回“真”。

To get a boolean result, you can test for not false like this.要获得布尔结果,您可以像这样测试not false (notice the use of !== which tries to match value and type. This avoids 0 giving you a false result). (注意使用!==尝试匹配值和类型。这避免了 0 给你一个错误的结果)。

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.另请注意,由于某些令人讨厌的原因,“haystack”和“needle”与许多其他 PHP 字符串函数相反,这很容易出错。

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 一起使用它:

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.使用preg_match()查找整个单词。

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文档: 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. strpos返回匹配字符串的位置,而不仅仅是匹配时。 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 .如果它在位置 0,则表示字符串以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否则,使用正则表达式答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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