Page 119 - Beginning PHP 5.3
P. 119
Chapter 5: Strings
You could find the number of occurrences easily enough using strpos() and a loop, but PHP, as in
most other things, gives you a function to do the job for you: substr_count() . To use it, simply pass
the string to search and the text to search for, and the function returns the number of times the text was
found in the string. For example:
$myString = “I say, nay, nay, and thrice nay!”;
echo substr_count( $myString, “nay” ); // Displays ‘3’
You can also pass an optional third argument to specify the index position to start searching, and an
optional fourth argument to indicate how many characters the function should search before giving up.
Here are some examples that use these third and fourth arguments:
$myString = “I say, nay, nay, and thrice nay!”;
echo substr_count( $myString, “nay”, 9 ) . “ < br / > ”; // Displays ‘2’
echo substr_count( $myString, “nay”, 9, 6 ) . “ < br / > ”; // Displays ‘1’
Searching for a Set of Characters with strpbrk()
What if you need to find out if a string contains any one of a set of characters? For example, you might
want to make sure a submitted form field doesn ’ t contain certain characters for security reasons. PHP
gives you a function, strpbrk() , that lets you easily carry out such a search. It takes two arguments: the
string to search, and a string containing the list of characters to search for. The function returns the
portion of the string from the first matched character to the end of the string. If none of the characters in
the set are found in the string, strpbrk() returns false .
Here are some examples:
$myString = “Hello, world!”;
echo strpbrk( $myString, “abcdef” ); // Displays ‘ello, world!’
echo strpbrk( $myString, “xyz” ); // Displays ‘’ (false)
$username = “matt@example.com”;
if ( strpbrk( $username, “@!” ) ) echo “@ and ! are not allowed in usernames”;
Replacing Text within Strings
As well as being able to search for text within a larger string, you can also replace portions of a string
with different text. This section discusses three useful PHP functions for replacing text:
❑ str_replace() replaces all occurrences of the search text within the target string
❑ substr_replace() replaces a specified portion of the target string with another string
❑ strtr() replaces certain characters in the target string with other characters
Replacing All Occurrences using str_replace()
str_replace() lets you replace all occurrences of a specified string with a new string. It ’ s the PHP
equivalent of using the Replace All option in a word processor.
81
c05.indd 81
c05.indd 81 9/21/09 8:53:42 AM
9/21/09 8:53:42 AM