I have a word with an escaped apostrophe in a string. I'm trying to use strpos to determine whether the word with the escaped apostrophe is in the string or not. Unfortunately, it echoes false every time. What am I doing wrong? I have tried, in strpos, with 1 escaped slash, 2 escaped slash, all the way up to 5, but it's echoing false every time.
$text = "example\'s";
$text = " ".$text." ";
if (strpos($text, " example\\\\\'s ")) {
echo "true.";
}
else {
echo "false.";
}
There are two problems here - the first is in your escaping of the string, and the second is in your logic based on the return from the strpos
function.
The first problem is that you don't need to escape the search input to strpos
- it's not a regex function!
The second problem is that your (unescaped) search string would match at position zero, which PHP also interprets as a false value.
The PHP strpos docs here state:
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.
Use this code instead which should work fine:
$text = "example\'s";
$text = " ".$text." ";
if (strpos($text, " example\'s ") === false) {
echo "false.";
} else {
echo "true.";
}
The ===
operator is the key here - it means equal value and type, so it prevents the PHP interpreter from treating a zero return as equal to false, which it otherwise would do.
See PHP's comparison operators reference: http://php.net/manual/en/language.operators.comparison.php
Edit: Further info on the values PHP considers to be false: -
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!