使用 strpos 在字符串中查找带有转义撇号的单词

Finding a word with an escaped apostrophe in a string using strpos

我有一个在字符串中带有转义撇号的单词。我正在尝试使用 strpos 来确定带有转义撇号的单词是否在字符串中。不幸的是,它每次都回响错误。我究竟做错了什么?我已经尝试过,在 strpos 中,使用 1 个转义斜杠,2 个转义斜杠,一直到 5 个,但每次都回显错误。

$text = "example\'s";
$text = " ".$text." ";

if (strpos($text, " example\\\'s ")) {
echo "true.";
}

else {
echo "false.";
}

这里有两个问题 - 第一个是你对字符串的转义,第二个是你基于 strpos 函数的 return 的逻辑。

第一个问题是您不需要将搜索输入转义为 strpos - 它不是正则表达式函数!

第二个问题是您的(未转义的)搜索字符串将匹配位置零,PHP 也将其解释为错误值。

PHPstrpos docs here状态:

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

改用这段代码应该可以正常工作:

$text = "example\'s";
$text = " ".$text." ";

if (strpos($text, " example\'s ") === false) {
    echo "false.";
} else {
    echo "true.";
}

=== 运算符是这里的关键 - 它意味着相等的值和类型,因此它阻止 PHP 解释器将零 return 视为等于 false,它否则就可以了。

参见PHP的比较运算符参考:http://php.net/manual/en/language.operators.comparison.php

编辑: 关于 PHP 认为错误的值的更多信息:-

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself

the integer 0 (zero)

the float 0.0 (zero)

the empty string, and the string "0"

an array with zero elements

an object with zero member variables (PHP 4 only)

the special type NULL (including unset variables)

SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Warning: -1 is considered TRUE, like any other non-zero (whether negative or positive) number!

发件人:http://php.net/manual/en/language.types.boolean.php