PHP strstr() function is used to find the first occurrence of a string inside another string. This function is case-sensitive.
Syntax
strstr($string, $search, $before_search)
Parameters
- $string(required): It is an input string.
- $search(required): It is the string you are searching for.
- $before_search(optional): The boolean value whose default is “false“. If it is set to “true”, it returns a part of the $string before the first occurrence of the $search parameter.
Return value
It returns the portion of the string or FALSE if the $search string is not found.
Visual Representation
Example 1: How to Use PHP strstr()
<?php
$str = "Hello CR7";
echo strstr($str,"CR7");
Output
CR7
Example 2: Search using ASCII valueSearch the string for an ASCII value of “l” and return the rest.
<?php
$str = "Hello CR7";
echo strstr($str,108);
Output
llo CR7
Example 3: Using the before_search parameter
<?php
$str = "Hello CR7";
echo strstr($str,"CR7", true);
Output
Hello
It returns the part of $str that comes before “CR7”.
The strstr() function is far more memory-intensive than strpos(), especially with a longer string.
So, if you are not interested in the substring that this function returns, you shouldn’t use it.
That’s it.