Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

strpos

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

like image 608
Scott B Avatar asked Aug 08 '11 19:08

Scott B


People also ask

What is the strpos () function used for?

The strpos() function finds the position of the first occurrence of a string inside another string.

Is string a string PHP?

Definition and UsageThe is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.

What is the use of strpos function in PHP Mcq?

Description: The strops() is in-built function of PHP. It is used to find the position of the first occurrence of a string inside another string or substring in a string.

Is Strpos case-sensitive PHP?

strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.


2 Answers

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.

like image 174
phihag Avatar answered Sep 28 '22 05:09

phihag


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)

like image 22
Rishabh Avatar answered Sep 28 '22 03:09

Rishabh