PHP Tutorial - PHP strstr() Function






Definition

The strstr() function its case-insensitive version, stristr() find the first occurrence of a substring.

Syntax

PHP strstr() Function has the following syntax.

string strstr ( string haystack, string needle [, flag] )

Parameter

  • haystack - The input string.
  • needle - If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
  • before_needle - If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).




Return

PHP strstr() Function returns all characters from the first occurrence to the end of the string.

Example

This next example will match the "www" part of the URL http://www.java2s.com/index.php, then return everything from the "www" until the end of the string:


<?PHP
$string = "http://www.java2s.com/index.php"; 
$newstring = strstr($string, "www"); 
print $newstring;
?>

The code above generates the following result.





Example 2

Tell if a sub string is found


<?PHP
$myString = "Hello, world!"; 
echo strstr( $myString, "wor" ) . "\n";                    // Displays 'world!' 
echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ) . " \n"; // Displays 'No'   
?>

The code above generates the following result.

Example 3

Returns the part of the haystack before the first occurrence of the needle (excluding the needle)


<?PHP
$myString = "Hello, world!"; 
echo strstr( $myString, "wor", true ); // Displays 'Hello, '    
?>

The code above generates the following result.