PHP – 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:

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 = "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.";

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).

The substr_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 of replacement in str. There are several behaviors you should keep in mind regarding the values of start and length:

If start is positive, replacement will begin at character start.

If start is negative, replacement will begin at str length – start.

If length is provided and is positive,replacement will be length characters long.

If length is provided and is negative,replacement will end at str length -length characters.

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:

$ccnumber = "1234567899991111";
echo substr_replace($ccnumber,"************",0,12);

This returns the following:


Leave a Reply

Your email address will not be published. Required fields are marked *