Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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|false

Parameters

ParameterTypeDescription
$haystackstringThe string to search in.
$needlestringWhat to look for.
$before_needleboolOptional. `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
anna

Notes

To merely check that a substring is present use str_contains() — it is faster and returns a bool.

See also

  • strpos — Finds the position of the first occurrence of a substring.
  • substr — Returns part of a string, counting in bytes.
  • explode — Splits a string into an array by a separator.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.