HomePHP Page 4 - Parsing Strings and Regular Expressions
Determining the Frequency of a String’s Appearance - 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).
$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. We'll own this space in three months. talk;
foreach($buzzwords as $bw) { echo "The word $bw appears ".substr_count($talk,$bw)." time(s).<br />"; } ?>
This returns the following:
-------------------------------------------- The word mindshare appears 1 time(s). The word synergy appears 1 time(s). The word space appears 2 time(s). --------------------------------------------
Replacing a Portion of a String with Another String
Thesubstr_replace()function replaces a portion of a string with a replacement string, beginning the substitution at a specified starting position and ending at a predefined replacement length. Its prototype follows:
string substr_replace(string str, string replacement, int start [, int length])
Alternatively, the substitution will stop on the complete placement ofreplacementinstr. There are several behaviors you should keep in mind regarding the values ofstartandlength:
Ifstartis positive,replacementwill begin at characterstart.
Ifstartis negative,replacementwill begin atstrlength -start.
Iflengthis provided and is positive,replacementwill belengthcharacters long.
Iflengthis provided and is negative,replacementwill end atstrlength -lengthcharacters.
Suppose you built an e-commerce site and within the user profile interface you want to show just the last four digits of the provided credit card number. This function is ideal for such a task: