strchr()
Our article is about the PHP function strchr(), which is used to find the first occurrence of a character in a string. In this article, we will discuss the
The PHP strchr() function finds the first occurrence of a substring inside a string and returns the rest of the string from that point on. Despite its name (which echoes C's strchr), the "needle" you search for can be more than a single character. This page covers the syntax, the optional $before_needle flag, the false return value you must guard against, and how strchr() relates to similar string functions.
Syntax
strchr(string $haystack, string $needle, bool $before_needle = false): string|falseThe function takes three parameters:
$haystack— the string being searched.$needle— the substring to look for. If it contains more than one character,strchr()matches the whole substring.$before_needle(optional) — whenfalse(the default) the part of the string from the match onward is returned; whentruethe part before the match is returned. Added in PHP 5.3.
It returns the matched portion of $haystack as a string, or false if $needle is not found.
Basic example
strchr() locates the first "o" in "Hello World" and returns the remainder of the string starting at that character:
o WorldReturning the part before the match
Pass true as the third argument to get everything before the first occurrence instead:
<?php
$string = "Hello World";
$result = strchr($string, "o", true);
echo $result;
?>HellThis is handy for splitting a string on a delimiter — for example, grabbing the local part of an email address by taking everything before "@".
Handling "not found"
When the needle is absent, strchr() returns false, not an empty string. Because false prints as nothing, an unchecked result can silently produce an empty output, so test it explicitly:
<?php
$result = strchr("Hello World", "z");
if ($result === false) {
echo "Not found";
} else {
echo $result;
}
?>Not foundUse the strict === comparison: a successful match could itself be the string "0", which == would treat as falsy.
strchr() vs. related functions
strstr()—strchr()is simply an alias ofstrstr(); they behave identically.strstr()is the more commonly used name.strpos()— returns the integer position of the first match (orfalse), rather than the matching substring. Use it when you need an index forsubstr()or other offset-based logic.substr()— extracts a portion of a string by numeric offset and length, with no searching involved.stristr()— the case-insensitive counterpart ofstrstr()/strchr().
Summary
strchr() finds the first occurrence of a needle in a string and returns the rest of the string (or, with $before_needle set to true, the part before it). Remember that it is an alias of strstr(), that the needle may be a multi-character substring, and that it returns false — which you should check with === — when nothing matches.