What is the stristr() method in PHP?
Overview
The stristr() method is similar to the strstr() function. You can refer to this shot to learn more about the strstr() function. In this shot, we take a look at the stritr() function.
The stritr() function compares two strings and returns all of the first string starting at the point where the second string was found in it. This comparison is case insensitive.
Syntax
Here is the syntax for the stritr() method:
stristr($haystack,$needle,$before_needle)
Parameter
-
$haystack: This is the string that will be searched and whose member characters will be compared with$needle. -
$needle: This the value to be searched for in$haystack. -
$before_needle: This is a true or false flag. It will determine if the value before$needlewill be returned instead of the part from the point where the needle is found in$haystack. The default value isfalse.
Return Value
If the $before_value parameter is not provided, a substring of $haystack including $needle, starting from the position of $needle in $haystack will be returned. Where $before_value is not provided, all of the string before $needle will be returned.
For the best output as intended,
$haystackhas to be a string value. This is because if an integer is provided, it will be converted to a string which will not give the best result.
Example
<?php$haystack = 'The love of this scrable game';echo stristr($haystack, 'this') ."\n"; // scrable gameecho stristr($haystack, 'this', true) ."\n"; // outputsthis$string = 'greetings there!';if(stristr($string, 'dear') === FALSE) {echo '"dear" not found in string';}// outputs: "dear" not found in string?>
Explanation
Following is the explanation of the code above:
- Line 3: We declare the
$haystackvariable. - Line 4: We use the
stristr()function to search for “this” in the$haystack. Here, the$before_valueparameter is not supplied, so the defaultfalseis used. - Line 5: We use the
stristr()function to search for “this” in the$haystack. Here, the$before_valueparameter is supplied astrue. Therefore, only the values before$thisare returned. - Line 7: We declare the
greetingvariable. - Line 8: We use an
ifstatement to check if a false value is output by thestristrfunction.