[Previous] [Contents] [Next]

Character lists

Rather than using a wildcard that matches any character, a list of characters enclosed in brackets can be specified within a pattern. For example, to match a three-character string that starts with a "p", ends with a "p", and contains a vowel as the middle letter, the expression:

ereg("p[aeiou]p", $var)

can be used. This returns true for any string that contains "pap", "pep", "pip", "pop", or "pup". A range of characters can also be specified; for example, "[0-9]" specifies the numbers 0 through 9:

// Matches "A1", "A2", "A3", "B1", ...
$found = ereg("[ABC][123]", "A1 Quality");  // true
// Matches "00" to "39"
$found = ereg("[0-3][0-9]", "27");  //true

A list can specify characters that aren't matches using the not operator ^ as the first character in the brackets. The pattern "[^123]" matches any character other than 1, 2, or 3. The following examples show more regular expressions that make use of the not operator in lists:

// true for "pap", "pbp", "pcp", etc. but not "php"
$found = ereg("p[^h]p", $val);
// true if $var does not contain
// alphanumeric characters
$found = ereg("[^0-9a-zA-Z]", $val);

The ^ character can be treated as normal by placing it in a position other than the start of the characters enclosed in the brackets. For example, "[0-9^]" matches the characters 0 to 9 and the ^ character. The - character can be matched by placing it at the start or the end of the list; for example, "[-123]" matches characters -, 1, 2, or 3.

Regex Anchors

A regular expression can specify that a pattern occur at the start or end of a subject string using anchors. The ^ anchors a pattern to the start, and the $ character anchors a pattern to the end of a string. For example, the expression:

 ereg("^php", $var)

matches strings that start with "php" but not others. The following code shows the operation of both:

$var = "to be or not to be";
$match = ereg("^to", $var); // true
$match = ereg('be$', $var); // true
$match = ereg("^or", $var); // false

Both anchors can be used in one regular expression to match a whole string. The following example illustrates this:

// Must match "Yes" exactly
$match = ereg('^Yes$', "Yes");     // true
$match = ereg('^Yes$', "Yes sir"); // false

[Previous] [Contents] [Next]