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

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

8 Answers

strpos returns false if the string is not found, and 0 if it is found at the beginning.

so try this:

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

Note we use a strict comparison (===) If we don't, both types (false and false or an integer) will be coerced to the same type, and 0 when coerced to a bool is false.

more details: https://zdevtips.com/guid/strpos-in-php-example4-example-codes/

This working for me when everything other fail in some situations:

$filename = 'my_upgrade(1).zip';
$match = 'my_upgrade';
$checker == false;
if(strpos($filename, $match))
    {
    $checker == true;
    }
if ($checker === false)
{ 
die();
}
else 
{
//proceed
}

Or in short:

$filename = 'my_upgrade(1).zip';
$match = 'my_upgrade';
$checker == false;
if(strpos($filename, $match))
    {
    $checker == true;
//proceed
 }
if ($checker === false)
{ 
die();
}

$data = 'match';
$line = 'match word in this line';
if(strpos($line,$data) !== false){
    echo "data found";
}else{
    echo "no data found";
}

Related