$filename = 'my_upgrade(1).zip';
$match = 'my_upgrade';
if(!strpos($filename, $match))
{
die();
}
else
{
//proceed
}
In the code above, I'm trying to die out of the script when the filename does not contain the text string "my_upgrade". However, in the example given, it should not die since "my_upgrade(1).zip" contains the string "my_upgrade".
What am I missing?
strpos in this case will return a zero, which is then interpretted as false when you do the logical negation. You should check explicitly for the boolean
false
.Otherwise,
strpos
will return0
(the index of the match), which isfalse
.The
===
operator will also compare type of the variables (boolean != integer)strpos
returnsfalse
if the string is not found, and0
if it is found at the beginning. Use the identity operator to distinguish the two:By the way, this fact is documented with a red background and an exclamation mark in the official documentation.
The
strpos()
function is case-sensitive.For using case-insensitive. use
stripos()
that is it finds the position of the first occurrence of a string inside another string (case-insensitive)The
strpos
functionDocs returnsfalse
if not found or0
if found on position0
(programmers like to start counting at0
often):This working for me when everything other fail in some situations:
Or in short: