PHP Reference ยท String Functions
PHP strstr() function
Reference for PHP strstr(): return the part of a string from the first match onward or before it, the before_needle flag, stristr() and email domains.
strstr() finds the first occurrence of a substring and returns the part of the string from that point to the end, including the needle itself. With the $before_needle flag set to true it returns the part before the needle instead. If the needle is not found it returns false.
It saves you from combining strpos() and substr() when you just want one side of a separator.
<?php echo strstr("[email protected]", "@"); // @example.com echo strstr("[email protected]", "@", true); // user
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
strstr(string $haystack, string $needle, bool $before_needle = false): string|false
| Name | Description |
|---|---|
$haystack |
The string to search in. |
$needle |
The substring to find. Since PHP 8.0 an empty needle is allowed and matches at the start. |
$before_needle |
If true, return the part before the first match (without the needle). If false (default), return from the match to the end. |
Return value: the selected part of $haystack as a string, or false if $needle is not found.
Usage notes
- Check for
false. Treat the result asstring|false; an uncheckedfalsesilently becomes""when used in string context. - First match only. To split at the last separator, use
strrchr()(single character) orstrrpos()withsubstr(). - Case-insensitive:
stristr()has the same parameters. - Needle is a string. Since PHP 8.0 a non-string needle is not treated as an ASCII code.
- Presence check only? Use
str_contains();strstr()copies a substring you may not need. - Byte-based. It is safe on UTF-8 text when the needle is valid UTF-8 as well, because UTF-8 sequences cannot match in the middle of another character.
- Parsing email addresses with
strstr()is fine for a quick split, but validate withfilter_var($s, FILTER_VALIDATE_EMAIL).
Related
strrchr(),strpos(),substr(),str_contains(),explode()- Lessons: Strings, String functions