strstr
Returns the part of a string starting at the first occurrence of a substring.
Syntax
strstr(string $haystack, string $needle, bool $before_needle = false): string|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $haystack | string | The string to search in. |
| $needle | string | What to look for. |
| $before_needle | bool | Optional. `true` returns the part before the occurrence. |
Return value
string|falsePart of the string, or `false` if the substring is not found.
Examples
The domain and the name from an email address:
<?php
$email = 'anna@example.com';
echo strstr($email, '@'), "\n";
echo strstr($email, '@', true);Output:
@example.com
annaNotes
To merely check that a substring is present use str_contains() — it is faster and returns a bool.
See also
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.