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/*  w w w  . java2  s  .  c o  m*/
$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/*from ww w . j a  v a 2  s .c  om*/
$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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions