PHP strstr() Function
In this chapter you will learn:
- Definition for PHP strstr() Function
- Syntax for PHP strstr() Function
- Parameter for PHP strstr() Function
- Return for PHP strstr() Function
- Example
- Example - tell if a sub string is found
- Example - returns the part of the haystack before the first occurrence of the needle (excluding the needle)
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/* j av a2 s . c om*/
$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/*j a va2s. c o m*/
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP strtok() Function
- Syntax for PHP strtok() Function
- Parameter for PHP strtok() Function
- Return for PHP strtok() Function
- Example - Split string one by one
Home » PHP Tutorial » PHP String Functions