All TalkersCode Topics

Follow TalkersCode On Social Media

Searching String In PHP

Last Updated : Jan 1, 2023

Searching String In PHP

In this tutorial we will show you the solution of searching string in PHP, there are many ways with help of which we can search string in php. Let us see the following example and code for better understanding.

As, there are already many function in php which helps us to search string in php. These are strpos(), strstr() and substr_count().

Step By Step Guide On Searching String In PHP :-

Let us understand them one by one with the help of codes. First, we use the objective of each function.

strstr() used for finding out required text in string

strops() used for finding out position of required text in string

substr_count() used to find out how many times a required string appears.

Now, let us understand the codes given below.

// you must have to run all these codes one by one for better understanding
$string = 'Hello, to talkers code!';
echo strstr( $string, 'to' );
$string = 'Hello, this is new string!';
if ( strstr( $string, 'that) ) {
  echo "Text found here";
} else {
  echo "Text not found here";
$string = 'Hello, to another string!';
echo strpos( $string, 'another' );
$string = 'Hello, to our website!';
echo strpos( $string, 'l' ) . '<br />';
echo strpos( $string, 'l', 2 ) . '<br />';
$string = 'Content writing is a job';
echo substr_count( $string, 'on' );
echo substr_count( $string, 'on', 0, 13 ) . '<br />';
echo substr_count( $string, 'on', 0, 7 ) . '<br />';
  1. As you see above, we show the codes of all the three methods with helps use to search strings in php. These all are the inbuilt functions used in php.
  2. And one thing more that we already discussed about that which function is used for what task. So, it is easy to understand now the above code.
  3. As, we see above that we use all the three function and we are not going to discuss the outputs here. It is better way to execute the code using own IDE and change the lines in code to see what happens in next output.
  4. Now, above first we store all the values or say strings in variables and then we use function on them. These all functions are echo to display output on screen.
  5. Here, strstr() function is used to find out that the string actually presents or not. Above two examples are given to see how to use them.
  6. Next one strops() is used to find out the position of required string. If the string is present in our string them it will give its position otherwise not.
  7. At last, we use stbstr_count(), this is another method of searching string. It returns us that how many times that text appears in our string.

Conclusion :-

At last in conclusion, here we can say that with the help of this article we are able to understand how search string in php.

I hope this tutorial on searching string in PHP helps you and the steps and method mentioned above are easy to follow and implement.

Latest Tutorials