HomePHP Page 2 - Parsing Strings and Regular Expressions
Finding the Last Occurrence of a String - PHP
In this fourth part of a five-part series on strings and regular expressions in PHP, you'll learn how to perform complex string parsing, find the last occurrence of a string, and more. This article is excerpted from chapter nine of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Thestrrpos()function finds the last occurrence of a string, returning its numerical position. Its prototype follows:
int strrpos(string str, char substr [, offset])
The optional parameteroffsetdetermines the position from whichstrrpos()will begin searching. Suppose you wanted to pare down lengthy news summaries, truncating the summary and replacing the truncated component with an ellipsis. However, rather than simply cut off the summary explicitly at the desired length, you want it to operate in a user-friendly fashion, truncating at the end of the word closest to the truncation length. This function is ideal for such a task. Consider this example:
<?php // Limit $summary to how many characters? $limit = 100;
$summary = <<< summary In the latest installment of the ongoing Developer.com PHP series, I discuss the many improvements and additions to <a href="http://www.php.net">PHP 5's</a> object-oriented architecture. summary;