There are four points to keep
in mind when using this function:
??? If start is positive, the returned string will begin at the start position of the string.
??? If start is negative, the returned string will begin at the length-start position of
the string.
??? If length is provided and is positive, the returned string will consist of the characters
between start and start + length. If this distance surpasses the total
string length, only the string between start and the string??™s end will be returned.
??? If length is provided and is negative, the returned string will end length characters
from the end of str.
Keep in mind that start is the offset from the first character of str; therefore, the
returned string will actually start at character position start + 1. Consider a basic
example:
CHAPTER 9 ?– S TRINGS AND REGULAR EXPRESS IONS 267
$car = "1944 Ford";
echo substr($car, 5);
?>
This returns the following:
Ford
The following example uses the length parameter:
$car = "1944 Ford";
echo substr($car, 0, 4);
?>
This returns the following:
1944
The final example uses a negative length parameter:
$car = "1944 Ford";
$yr = echo substr($car, 2, -5);
?>
This returns the following:
44
Determining the Frequency of a String??™s Appearance
The substr_count() function returns the number of times one string occurs within
another. Its prototype follows:
268 CHAPTER 9 ?– STRINGS AND REGULAR EXPRESSIONS
int substr_count(string str, string substring)
The following example determines the number of times an IT consultant uses various
buzzwords in his presentation:
$buzzwords = array("mindshare", "synergy", "space");
$talk = <<< talk
I'm certain that we could dominate mindshare in this space with
our new product, establishing a true synergy between the marketing
and product development teams.
Pages:
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343