Page 124 - Open Soource Technologies 304.indd
P. 124
Web Technologies-I
Notes
ereg(“ab+a”, $var)
so while strings such as “aba”, “abba”, and “abbba” match, “aa” does not.
The operators ?, *, and + can also be used with a wildcard or a list of characters. The following
examples show you how:
$var = “www.example.edu.au”;
// True for strings that start with “www” and end with “au”
$matches = ereg(‘^www.*au$’, $var); // true
$hexString = “x01ff”;
// True for strings that start with ‘x’ followed by at least
// one hexadecimal digit
$matches = ereg(‘x[0-9a-fA-F]+$’, $hexString); // true
The first example matches any string that starts with “www” and ends with “au”; the pattern “.*”
matches a sequence of any characters, including an empty string. The second example matches
any sequence that starts with the character “x” followed by one or more characters from the list
[0-9a-fA-F].
A fixed number of occurrences can be specified in braces. For example, the pattern “[0-7]{3}”
matches three-character numbers that contain the digits 0 through 7:
$valid = ereg(“[0-7]{3}”, “075”); // true
$valid = ereg(“[0-7]{3}”, “75”); // false
The braces syntax also allows the minimum and maximum occurrences of a pattern to be specified
as demonstrated in the following examples:
$val = “58273”;
// true if $val contains numerals from start to end
// and is between 4 and 6 characters in length
$valid = ereg(‘^[0-9]{4,6}$’, $val); // true
$val = “5827003”;
$valid = ereg(‘^[0-9]{4,6}$’, $val); // false
// without the anchors at the start and end, the
// matching pattern “582768” is found
$val = “582768986456245003”;
$valid = ereg(“[0-9]{4,6}”, $val); // true
Groups
Subpatterns in a regular expression can be grouped by placing parentheses around them. This
allows the optional and repeating operators to be applied to groups rather than just a single
character.
118 LOVELY PROFESSIONAL UNIVERSITY