strstr():Searching for a match inside a string

Find the first matching substring with strstr()

strstr() returns the part of the haystack beginning with the first match, or false when the needle is absent. Use a strict false check when the result controls program logic. If you only need a yes/no existence check, str_contains() is clearer for current PHP.

$text = 'Learn PHP strings';
$match = strstr($text, 'PHP');
if ($match !== false) {
    echo $match; // PHP strings
}

Use strstr() when you need the substring starting at the first case-sensitive match. Check for false before using the result.

$haystack="myuserid@example.com";
$needle="@";
echo strstr($haystack,$needle,false);// @example.com
Output is
@example.com
Syntax
echo strstr($haystack,$needle,$before);
$haystack
Required: Input string ( main string for searching )
$needle
Required: used to search the first occurrence inside Input string
$before
Optional: default FALSE, if set to TRUE then output returns the string before the first occurrence of $needle ( excluding the $needle )
Output is the part of string after the needle ( if $before is FALSE ) or before the needle. FALSE is returned if matching is not found.

This is case sensitive search. Use stristr() for case in-sensitive search
$haystack="myuserid@example.com";
$needle="@";
echo strstr($haystack,$needle,true);// myuserid
Output is
myuserid

Example of strstr()

$haystack="Welcome to plus2net.com to learn PHP";
$needle="to";
echo strstr($haystack,$needle);// to plus2net.com to learn PHP
Output is
to plus2net.com to learn PHP

When to use strstr()

strstr() extracts the suffix beginning at the first case-sensitive match. To extract an email domain after validating the address, search for @:

$email = 'myname@example.com';
$at = strstr($email, '@');
if ($at !== false) {
    echo substr($at, 1); // example.com
}

For a case-insensitive substring match, see stristr(). Finding https:// or <a in input is not reliable link detection or input sanitization. Validate submitted URLs separately, escape text with htmlspecialchars() before HTML output, and allow HTML only through an appropriate sanitizer.

Searching Blank space inside a string

$string='first second';
if (strstr($string,' ')) {
echo " There is blank space present inside the string ";
}else{
echo " There is NO blank space present inside the string ";
}
The output is
 There is blank space present inside the string

String Functions stristr(): case-insensitive search


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer