Page 121 - Open Soource Technologies 304.indd
P. 121
Unit 5: Strings
Notes
This function tests whether a string holds an octal number.
function is_octal ($str) { return strspn($str, ‘01234567’) == strlen($str); }
The c in strcspn( ) stands for complement—it tells you how much of the start of the string is not
composed of the characters in the character set. Use it when the number of interesting characters
is greater than the number of uninteresting characters. For example, this function tests whether
a string has any NUL-bytes, tabs, or carriage returns:
function has_bad_chars ($str) { return strcspn($str, “\n\t\0”); }
Decomposing URLs
The parse_url( ) function returns an array of components of a URL:
$array = parse_url(url);
Example:
$bits = parse_url(‘http://me:secret@example.com/cgi-bin/board?user=Pradip);
print_r($bits);
Array ( [scheme] => http [host] => example.com [user] => me [pass] => secret [path] => /cgi-bin/
board [query] => user=Pradip )
The possible keys of the hash are scheme, host, port, user, pass, path, query, and fragment.
PHP imposes no boundary on the size of a string; the only limit is the available
memory of the computer on which PHP is running.
5.8 Regular Expressions
In this, we show how regular expressions can achieve more sophisticated pattern matching to
find, extract, and replace complex substrings within a string. While regular expressions provide
capabilities beyond those described in the last, complex pattern matching is not as efficient as
simple string comparisons.
This begins with a brief description of the POSIX regular expression syntax. This is not a
complete description of all of the capabilities, but we do provide enough details to create quite
powerful regular expressions. The second half of it describes the functions that use POSIX regular
expressions.
5.8.1 Regular Expression Syntax
A regular expression follows a strict syntax to describe patterns of characters. PHP has two sets of
functions that use regular expressions: one set supports the Perl Compatible Regular Expression
(PCRE) syntax, and the other supports the POSIX extended regular expression syntax. In this
book, we use the POSIX functions.
To demonstrate the syntax of regular expressions, we introduce the function ereg( ) :
boolean ereg(string pattern, string subject [, array var])
ereg( ) returns true if the regular expression pattern is found in the subject string. We discuss how
the ereg( ) function can extract values into the optional array variable var.
The following trivial example shows how ereg( ) is called to find the literal pattern cat in the subject
string “raining cats and dogs”:
LOVELY PROFESSIONAL UNIVERSITY 115