Page 118 - Beginning PHP 5.3
P. 118
Part II: Learning the Language
strpos() can take an optional third argument: an index position within the string to start the search.
Here ’ s an example:
$myString = “Hello, world!”;
echo strpos( $myString, “o” ) . “ < br/ > ”; // Displays ‘4’
echo strpos( $myString, “o”, 5 ) . “ < br/ > ”; // Displays ‘8’
You can use this third argument, combined with the fact that strpos() returns the position of the
matched text, to repeatedly find all occurrences of the search text within the string — for example:
$myString = “Hello, world!”;
$pos = 0;
while ( ( $pos = strpos( $myString, “l”, $pos ) ) !== false ) {
echo “The letter ‘l’ was found at position: $pos < br/ > ”;
$pos++;
}
This code produces the output shown in Figure 5 - 1 .
Figure 5 - 1
strpos() has a sister function, strrpos() , that does basically the same thing; the only difference is that
strrpos() finds the last match in the string, rather than the first:
$myString = “Hello, world!”;
echo strpos( $myString, “o” ) . “ < br / > ”; // Displays ‘4’
echo strrpos( $myString, “o” ) . “ < br / > ”; // Displays ‘8’
As with strpos() , you can pass an optional third argument indicating the index position from which to
start the search. If this index position is negative, strrpos() starts that many characters from the end of
the string, rather than from the beginning.
Finding the Number of Occurrences with substr_count()
Occasionally you might need to know how many times some text occurs within a string. For example, if
you were writing a simple search engine, you could search a string of text for a keyword to see how
relevant the text is for that keyword; the more occurrences of the keyword, the greater the chance that the
text is relevant.
80
9/21/09 8:53:41 AM
c05.indd 80 9/21/09 8:53:41 AM
c05.indd 80