Chapter 9
Chapter 9
9 expreSSionS
The strpos() function finds the position of the first case-sensitive occurrence of a
substring in a string. Its prototype follows:
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;
This returns the position in which the file index.html is first accessed:
The function stripos() operates identically to strpos(), except that it executes its
search case insensitively.
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;
The most up to date source for PHP documentation is the PHP manual. It
contins many...
The str_replace() function case sensitively replaces all instances of a string with
another. Its prototype follows:
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.";
?>
The strstr() function returns the remainder of a string beginning with the first
occurrence of a predefined string. Its prototype follows:
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, "@"),"@");
?>
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:
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
<?php
$car = "1944 Ford";
echo substr($car, 0, 4);
?>
This returns the following:
1944
<?php
$car = "1944 Ford";
echo substr($car, 2, -5);
?>
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:
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");
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.
<?php
$ccnumber = "1234567899991111";
echo substr_replace($ccnumber,"************",0,12);
?>
************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.";
?>
Salad is good.
<?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.
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.
The function count_chars() offers information regarding the characters found in a string.
This function only works on single byte characters. Its prototype follows:
1: Same as 0, but returns only those byte values with a frequency greater
than zero.
<?php
$sentence = "The rain in Spain falls mainly on the plain";
foreach($chart as $letter=>$frequency)
echo "Character ".chr($letter)." appears $frequency times<br
/>";
?>
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:
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);
?>
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);
?>
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 )