Search code examples
phpstrpos

How to use strpos to determine if a string exists in input string?


$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?


Solution

  • strpos returns false if the string is not found, and 0 if it is found at the beginning. Use the identity operator to distinguish the two:

    if (strpos($filename, $match) === false) {
    

    By the way, this fact is documented with a red background and an exclamation mark in the official documentation.