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;
-------------------------------------------- In the latest installment of the ongoing Developer.com PHP series, I discuss the many... --------------------------------------------
Replacing All Instances of a String with Another String
Thestr_replace()function case sensitively replaces all instances of a string with another. Its prototype follows:
mixed str_replace(string occurrence, mixed replacement, mixed str [, int count])
Ifoccurrenceis not found instr, the original string is returned unmodified. If the optional parametercount is defined, onlycount occurrences found instrwill be replaced.
This function is ideal for hiding e-mail addresses from automated e-mail address retrieval programs:
<?php $author = jason@example.com; $author = str_replace("@","(at)",$author); echo "Contact the author of this article at $author."; ?>
This returns the following:
-------------------------------------------- Contact the author of this article at jason(at)example.com. --------------------------------------------
The functionstr_ireplace()operates identically tostr_replace(), except that it is capable of executing a case-insensitive search.