PHP Function Reference

PHP strstr() Function



The PHP strstr() function returns a string which starts from first occurrence of the search string to the end of the given string.

The function has one optional parameter. The default value of this parameter is false. If this is set to true, the function returns string from start of the given string to the first occurrence of the search string.

This function is same as stristr() function, except this function is a case-sensitive function.

Note: The strstr() function is a binary-safe and a case-sensitive function.

Syntax

strstr(string, search, before_search)

Parameters

string Required. Specify the string to search.
search Required. Specify the string to search for in the given string.
Prior to PHP 8.0.0, if it is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0. Depending on the intended behavior, this should either be explicitly cast to string, or an explicit call to chr() should be performed.
before_search Optional. If set to true, the function returns string from start to the first occurrence of the specified text. Default is false.

Return Value

  • If the third parameter is set to false, it returns a string starting from first occurrence of the search string to the end of the given string.
  • If the third parameter is set to true, it returns a string starting from the start of the given string to the first occurrence of the search string in the given string.
  • Returns false if search string is not found.

Example: strstr() example

The example below shows the usage of strstr() function.

<?php
$str = "To be, or not to be, that is the question";

//displaying a portion of $str starting from 
//first found "not" to the end of it
echo strstr($str, "not")."\n";

//displaying a portion of $str starting from 
//beginning of it to the first found "not"
echo strstr($str, "not", true)."\n";
?>

The output of the above code will be:

not to be, that is the question
To be, or 

Example: strstr() example

The example below demonstrates on using this function in various scenarios.

<?php
//getting the username
$email  = 'john123@example.com';
$user = strstr($email, "@", true);
echo $user."\n";

$path = "var/etc/fig/example.jpg";
//getting the first directory 
$dir = strstr($path, "/", true);
echo $dir."\n";

//getting everything before first newline
$text = "Line 1\nLine 2\nLine 3";
$first = strstr($text, "\n", true);
echo $first."\n";
?>

The output of the above code will be:

john123
var
Line 1

❮ PHP String Reference