How to Find First Occurrence in String - strstr() and stristr() Function

PHP String Functions

The strstr() and stristr() functions find the first occurrence of a substring (second parameter) inside another string (first parameter), and return all characters from the first occurrence till the end of the string.

images/articles/php/find-first-occurrence-in-string-strstr-and-stristr.jpg

The strstr() function is case-sensitive and the stristr() is case-insensitive.

Syntax

strstr(string $haystack, string $needle, bool $before_needle = false)

Parameters

  1. haystack (Required) - Where to search; Specifies the string to search.
  2. needle (Required) - What to search; Specifies the string to search for.
  3. before_needle (Optional) - A boolean value whose default is "false". If set to "true", it returns the part of the string before the first occurrence of the search parameter.

Example

<?php
$email = 'user@example.com';
echo strstr($email, '@');
echo strstr($email, '@', true);
?>

The first function looks for the first occurrence of the "@" symbol in the $email variable and returns the substring starting from the "@" symbol to the end of the string.

The second function returns the portion of the string before the first occurrence of the substring. In this case, it returns the substring before the "@" symbol.