How to find the presence of a string inside a string in PHP? (PHP find string in string)

In some situation, we may want to find whether a string is present inside a string in PHP. Lets see how can we check whether the string contains a particular string.

PHP find string in string

We can achieve this requirement in so many ways. Following two solutions are the easiest approach. 

Solution 01

To find whether a string contains a particular string then we can use preg_match function. 

Syntax

preg_match(pattern, subject)

  • preg_match function takes two parameter. First one is the pattern (i.e the desired string) and the second parameter is the target string. 
  • We always keep the pattern in between forward slashes (/) and in between single or double quote.
Example:

Lets consider a string variable contains the following string value.

We had paratha, butter chicken, paneer chilly and coke at the restaurant

Now, lets check whether the string contains paratha or not. 


<?php
$mainString="We had paratha, butter chicken, paneer chilly and coke at the restaurant";
if(preg_match('/paratha/', $mainString)){
echo "It contains Paratha";
}
preg_match(pattern, subject)
?>

Output:

It contains Paratha

Solution 02

There is best alternate solution to preg_match function and that strpos function

  • strpos checks the first occurrence of a string inside another string. 
  • If it finds then it prints the position of the desired string inside a target string.
  • strpos takes two parameters. First parameter is the target string and the second parameter is the desired string. 
Example:

<?php
$mainString="We had paratha, butter chicken, paneer chilly and coke at the restaurant";
echo strpos($mainString, "paratha");
?>
Output:

7

With the help of 'if condition', instead of string position we can check whether the string is present inside a target string.

<?php
$mainString="We had paratha, butter chicken, paneer chilly and coke at the restuarant";
if(strpos($mainString, "paratha")!==false){
echo "It contains the string paratha";
}
?>
Output:
It contains the string paratha
How to find the presence of a string inside a string in PHP? (PHP find string in string) How to find the presence of a string inside a string in PHP? (PHP find string in string) Reviewed by Pixel Stream on December 09, 2019 Rating: 5

No comments:

Powered by Blogger.