stristr
and stripos
are string functions in PHP that are used for case-insensitive searching within strings. They are useful for finding occurrences of substrings regardless of their letter casing. Here’s an explanation of each function:
stristr
function:
- Syntax:
stristr(string $haystack, mixed $needle, bool $before_needle = false)
- Returns: Returns the portion of
$haystack
starting from the first occurrence of$needle
(case-insensitive), orfalse
if$needle
is not found. - The optional
$before_needle
parameter, when set totrue
, returns the portion of the haystack before the needle.
Example:
$string = "Hello, world!";
$substring = "world";
$result = stristr($string, $substring); // Returns "world!"
stripos
function:
- Syntax:
stripos(string $haystack, string $needle, int $offset = 0)
- Returns: Returns the numeric position of the first occurrence of
$needle
in$haystack
(case-insensitive), orfalse
if$needle
is not found. - The optional
$offset
parameter allows you to start searching from a specific position within the haystack.
Example:
$string = "Hello, world!";
$substring = "World";
$position = stripos($string, $substring); // Returns 7
Here’s how you might use these functions:
$string = "Hello, world!";
$substring = "World";
// Using stristr to get the portion of the string
$portion = stristr($string, $substring);
echo $portion; // Outputs "world!"
// Using stripos to get the position of the substring
$position = stripos($string, $substring);
if ($position !== false) {
echo "Substring found at position: $position";
} else {
echo "Substring not found";
}
Keep in mind that both stristr
and stripos
are case-insensitive, so they can be very useful when you want to search for substrings in a way that doesn’t depend on letter casing.