Page 117 - Beginning PHP 5.3
P. 117
Chapter 5: Strings
❑ strstr() tells you whether the search text is within the string
❑ strpos() and strrpos() return the index position of the first and last occurrence of the search
text, respectively
❑ substr_count() tells you how many times the search text occurs within the string
❑ strpbrk() searches a string for any of a list of characters
Searching Strings with strstr()
If you just want to find out whether some text occurs within a string, use strstr() . This takes two
parameters: the string to search through, and the search text. If the text is found, strstr() returns the
portion of the string from the start of the found text to the end of the string. If the text isn ’ t found, it
returns false . For example:
$myString = “Hello, world!”;
echo strstr( $myString, “wor” ) . “ < br / > ”; // Displays ‘world!’
echo ( strstr( $myString, “xyz” ) ? “Yes” : “No” ) . “ < br / > ”; // Displays ‘No’
As of PHP 5.3, you can also pass an optional third Boolean argument. The default value is false . If you
pass in a value of true , strstr() instead returns the portion from the start of the string to the character
before the found text:
$myString = “Hello, world!”;
echo strstr( $myString, “wor”, true ); // Displays ‘Hello, ‘
Locating Text with strpos() and strrpos()
To find out exactly where a string of text occurs within another string, use strpos() . This function
takes the same two parameters as strstr() : the string to search, and the search text to look for. If the
text is found, strpos() returns the index of the first character of the text within the string. If it ’ s not
found, strpos() returns false :
$myString = “Hello, world!”;
echo strpos( $myString, “wor” ); // Displays ‘7’
echo strpos( $myString, “xyz” ); // Displays ‘’ (false)
There ’ s a gotcha when the searched text occurs at the start of the string. In this case, strpos() returns 0
(the index of the first character of the found text), but it ’ s easy to mistake this for a return value of false
if you ’ re not careful. For example, the following code will incorrectly display “Not found” :
$myString = “Hello, world!”;
if ( !strpos( $myString, “Hel” ) ) echo “Not found”;
So you need to test explicitly for a false return value, if that ’ s what you ’ re checking for. The following
code works correctly:
$myString = “Hello, world!”;
if ( strpos( $myString, “Hel” ) === false ) echo “Not found”;
79
9/21/09 8:53:41 AM
c05.indd 79
c05.indd 79 9/21/09 8:53:41 AM