0% found this document useful (0 votes)
83 views11 pages

Chapter 9

This document discusses various PHP string functions including: 1) strpos() and stripos() which find the position of a substring in a string in a case-sensitive or case-insensitive manner. 2) strrpos() which finds the last occurrence of a substring in a string. 3) str_replace() and str_ireplace() which replace all occurrences of a substring with another string in a case-sensitive or case-insensitive way. 4) substr(), substr_count(), and substr_replace() which allow extracting or replacing portions of a string.

Uploaded by

Ahmadullah Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views11 pages

Chapter 9

This document discusses various PHP string functions including: 1) strpos() and stripos() which find the position of a substring in a string in a case-sensitive or case-insensitive manner. 2) strrpos() which finds the last occurrence of a substring in a string. 3) str_replace() and str_ireplace() which replace all occurrences of a substring with another string in a case-sensitive or case-insensitive way. 4) substr(), substr_count(), and substr_replace() which allow extracting or replacing portions of a string.

Uploaded by

Ahmadullah Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter StringS and regular

9 expreSSionS

Performing Complex String Parsing

The strpos() function finds the position of the first case-sensitive occurrence of a
substring in a string. Its prototype follows:

int strpos(string str, string substr [, int offset])

The optional input parameter offset specifies the position at which to begin the search. If
substr is not in str, strpos() will return FALSE. The optional parameter offset determines the
position from which strpos() will begin searching. The following example determines the
timestamp of the first time index.html accessed:
<?php
$substr = "index.html";
$log = <<< logfile 192.168.1.11:/www/htdocs/index.html:
[2010/02/10:20:36:50] 192.168.1.13:/www/htdocs/about.html:
[2010/02/11:04:15:23] 192.168.1.15:/www/htdocs/index.html:
[2010/02/15:17:25]
logfile;

// What is first occurrence of the time $substr in log?


$pos = strpos($log, $substr);

// Find the numerical position of the end of the line


$pos2 = strpos($log,"\n",$pos);

// Calculate the beginning of the timestamp


$pos = $pos + strlen($substr) + 1;

// Retrieve the timestamp


$timestamp = substr($log,$pos,$pos2-$pos);
echo "The file $substr was first accessed on: $timestamp";
?>

This returns the position in which the file index.html is first accessed:

The file index.html was first accessed on: [2010/02/10:20:36:50]

The function stripos() operates identically to strpos(), except that it executes its
search case insensitively.

Finding the Last Occurrence of a String

The strrpos() function finds the last occurrence of a string, returning its numerical
position. Its prototype follows:
1
Chapter StringS and regular
int strrpos(string str, char substr [, offset]) 9 expreSSionS

The optional parameter offset determines the position from which strrpos() 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


The most up to date source for PHP documentation is the PHP manual. It
contins many examples and user contributed code and comments.
It is available on the main PHP web site
<a href="http://www.php.net">PHP’s</a>.
summary;

if (strlen($summary) > $limit)


$summary = substr($summary, 0, strrpos(substr($summary, 0, $limit), ' '))
. '...';
echo $summary;
?>

This returns the following:

The most up to date source for PHP documentation is the PHP manual. It
contins many...

Replacing All Instances of a String with Another String

The str_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])

If occurrence is not found in str, the original string is returned unmodified. If the optional
parameter count is defined, only count occurrences found in str will be replaced.
This function is ideal for hiding e-mail addresses from automated e-mail address retrieval
programs:

2
Chapter StringS and regular
<?php 9 expreSSionS
$author = "[email protected]";
$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 function str_ireplace() operates identically to str_replace(), except that it is


capable of executing a case-insensitive search.

Retrieving Part of a String

The strstr() function returns the remainder of a string beginning with the first
occurrence of a predefined string. Its prototype follows:

string strstr(string str, string occurrence [, bool before_needle])

The optional before_needle parameter modifies the behavior of strstr(), causing the
function to instead return the part of the string that is found before the first occurrence.
This example uses the function in conjunction with the ltrim() function to retrieve the
domain name of an e-mail address:

<?php
$url = "[email protected]";
echo ltrim(strstr($url, "@"),"@");
?>

This returns the following:

example.com
Returning Part of a String Based on Predefined Offsets

The substr() function returns the part of a string located between a predefined starting
offset and length positions. Its prototype follows:

string substr(string str, int start [, int length])

If the optional length parameter is not specified, the substring is considered to be the
string starting at start and ending at the end of str. 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.

3
Chapter StringS and regular
• If start is negative, the returned string at the length -
9 will begin expreSSionS
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 and strings (like arrays) are
0 indexed. Consider a basic example:

<?php
$car = "1944 Ford";
echo substr($car, 5);
?>

This returns the following starting from the sixth character at position 5:

Ford

The following example uses the length parameter:

<?php
$car = "1944 Ford";
echo substr($car, 0, 4);
?>
This returns the following:

1944

The final example uses a negative length parameter:

<?php
$car = "1944 Ford";
echo substr($car, 2, -5);
?>

This returns the following:

44

4
Chapter StringS and regular
Determining the Frequency of a String’s Appearance9 expreSSionS

The substr_count() function returns the number of times one string occurs within
another. This function is case sensitive. Its prototype follows:

int substr_count(string str, string substring [, int offset [, int length]])

The optional offset and length parameters determine the string offset from which to begin
attempting to match the substring within the string, and the maximum length of the string to
search following the offset, respectively.
The following example determines the number of times an IT consultant uses
various buzzwords in his presentation:

<?php
$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. 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

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:

5
Chapter StringS and regular
• If start is positive, replacement will 9begin at character start.
expreSSionS
• 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:

<?php
$ccnumber = "1234567899991111";
echo substr_replace($ccnumber,"************",0,12);
?>

This returns the following:

************1111

Padding a String

The str_pad() function pads a string with a specified number of characters. Its
prototype follows:

string str_pad(string str, int length [, string pad_string [, int pad_ type]])

If the optional parameter pad_string is not defined, str will be padded with blank spaces;
otherwise, it will be padded with the character pattern specified by pad_string. By default, the
string will be padded to the right; however, the optional parameter pad_type may be assigned the
values STR_PAD_RIGHT (the default), STR_PAD_LEFT, or STR_PAD_BOTH, padding the string
accordingly. This example shows how to pad a string using this function:

<?php
echo str_pad("Salad", 10)." is good.";
?>

This returns the following:

Salad is good.

This example makes use of str_pad()’s optional parameters:

<?php

6
Chapter StringS and regular
$header = "Log Report"; 9 expreSSionS
echo str_pad ($header, 20, "=+", STR_PAD_BOTH);
?>

7
This returns the following:

=+=+=Log Report=+=+=

Note that str_pad() truncates the pattern defined by pad_string if the length is
reached before completing an entire repetition of the pattern.

Counting Characters and Words

It’s often useful to determine the total number of characters or words in a given string.
Although PHP’s considerable capabilities in string parsing has long made this task trivial, the
following two functions were added to formalize the process.

Counting the Number of Characters in a String

The function count_chars() offers information regarding the characters found in a string.
This function only works on single byte characters. Its prototype follows:

mixed count_chars(string str [, int mode])

Its behavior depends on how the optional parameter mode is defined:

0: Returns an array consisting of each found byte value (0- 255


representing each possible character) as the key and the
corresponding frequency as the value, even if the frequency is
zero. This is the default.

1: Same as 0, but returns only those byte values with a frequency greater
than zero.

2: Same as 0, but returns only those byte values with a frequency of


zero.

3: Returns a string containing all located byte values.

4: Returns a string containing all unused byte values.


The following example counts the frequency of each character in
$sentence:

<?php
$sentence = "The rain in Spain falls mainly on the plain";

// Retrieve located characters and their corresponding


frequency.
$chart = count_chars($sentence, 1);

foreach($chart as $letter=>$frequency)
echo "Character ".chr($letter)." appears $frequency times<br
/>";
?>

This returns the following:

Character appears 8 times

Character S appears 1 times


Character T appears 1 times
Character a appears 5 times
Character e appears 2 times
Character f appears 1 times
Character h appears 2 times
Character i appears 5 times
Character l appears 4 times
Character m appears 1 times
Character n appears 6 times
Character o appears 1 times
Character p appears 2 times
Character r appears 1 times
Character s appears 1 times
Character t appears 1 times
Character y appears 1 times

Counting the Total Number of Words in a String

The function str_word_count() offers information regarding the total number of words found
in a string. Words are defined as a string of alphabetical characters, depending on the local
setting, and may contain but not start with – and ’. Its prototype follows:

mixed str_word_count(string str [, int format])

If the optional parameter format is not defined, it will return the total number of words. If format is
defined, it modifies the function’s behavior based on its value:
1: Returns an array consisting of all words located in str.

2: Returns an associative array where the key is the numerical position of the
word in str and the value is the word itself.

Consider an example:

<?php
$summary = <<< summary
The most up to date source for PHP documentation is the PHP manual. It
contins many examples and user contributed code and comments.
It is available on the main PHP web site
<a href="http://www.php.net">PHP's</a>.
summary;
$words = str_word_count($summary); printf("Total
words in summary: %s", $words);
?>

This returns the following:

Total words in summary: 41

You can use this function in conjunction with array_count_values() to determine the
frequency in which each word appears within the string:

<?php
$summary = <<< summary
The most up to date source for PHP documentation is the PHP manual. It
contins many examples and user contributed code and comments.
It is available on the main PHP web site
<a href="http://www.php.net">PHP’s</a>.
summary;
$words = str_word_count($summary,2);
$frequency = array_count_values($words);
print_r($frequency);
?>

This returns the following:

Array ( [The] => 1 [most] => 1 [up] => 1 [to] => 1 [date] => 1 [source] => 1 [for] =>
1 [PHP] => 4 [documentation] => 1 [is] => 2 [the] => 2 [manual]
=> 1 [It] => 2 [contins] => 1 [many] => 1 [examples] => 1 [and] => 2 [user] => 1
[contributed] => 1 [code] => 1 [comments] => 1 [available] => 1 [on] => 1 [main] => 1
[web] => 1 [site] => 1 [a] => 2 [href] => 1 [http]
=> 1 [www] => 1 [php] => 1 [net] => 1 [s] => 1 )

You might also like