[Previous] [Contents] [Next]

Optional and repeating characters

By following a character in a regular expression with a ?, *, or + operator, the pattern matches zero or one, zero to many, or one to many occurrences of the character, respectively.

The ? operator allows zero or one occurrence of a character, so the expression:

 ereg("pe?p", $var)

matches either "pep" or "pp", but not the string "peep". The * operator allows zero or many occurrences of the "o" in the expression:

 ereg("po*p", $var)

and matches "pp", "pop", "poop", "pooop", and so on. Finally, the + operator allows one to many occurrences of "b" in the expression:

 ereg("ab+a", $var)

so while strings such as "aba", "abba", and "abbba" match, "aa" doesn't.

The operators ?, *, and + can also be used with a wildcard or a list of characters. The following examples show how:

$var = "www.rmit.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 a blank 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

[Previous] [Contents] [Next]