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

后端 未结 7 1553
难免孤独
难免孤独 2020-12-03 17:17
$filename = \'my_upgrade(1).zip\';
$match = \'my_upgrade\';

if(!strpos($filename, $match))
    {
    die();
    }
else 
   {
   //proceed
   }

In

相关标签:
7条回答
  • 2020-12-03 17:26

    The strpos() function is case-sensitive.

    if(strpos($filename, $match) !== false)
            {
            // $match is present in $filename
            }
        else 
           {
           // $match is not present in $filename 
           }
    

    For using case-insensitive. use stripos() that is it finds the position of the first occurrence of a string inside another string (case-insensitive)

    0 讨论(0)
  • 2020-12-03 17:27

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

    0 讨论(0)
  • 2020-12-03 17:32

    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.

    0 讨论(0)
  • 2020-12-03 17:34

    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.

    0 讨论(0)
  • 2020-12-03 17:37
    if (strpos($filename, $match) === false)
    

    Otherwise, strpos will return 0 (the index of the match), which is false.

    The === operator will also compare type of the variables (boolean != integer)

    0 讨论(0)
  • 2020-12-03 17:45

    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();
    }
    
    0 讨论(0)
提交回复
热议问题