PHP and Regular Expressions 101 - The regular expression syntax (contd.) (Page 4 of 6 )
The space character
To match the space character in a search string, we use the predefined Posix class, [[:space:]]. The square brackets indicate a related set of sequential characters, and ":space:" is the actual class to match (which, in this case, is any white space character). White spaces include the tab character, the new line character, and the space character. Alternatively, you could use one space character (" ") if the search string must contain just one space and not a tab or new line character. In most circumstances I prefer to use ":space:" because it signifies my intentions a bit better than a single space character, which can easy be overlooked. There are several Posix-standard predefined classes that we can match as part of a regular expression, including [:alnum:], [:digit:], [:lower:], etc. A complete list is available here.
Related patterns can be grouped together between square brackets. It's really easy to specify that a lower case only or upper case only sequence of characters should exist as part of the search string using [a-z] and [A-Z], like this:
// Require all lower case characters from first to last
echo ereg("^[a-z]+$", "johndoe"); // Returns true
or like this:
// Require all upper case characters from first to last
ereg("^[A-Z]+$", "JOHNDOE"); // Returns true?
We can also tell the regular expression engine that we expect either lower case or upper case characters. We do this by joining the [a-z] and [A-Z] patterns:
<?php echo ereg("^[a-zA-Z]+$", "JohnDoe"); ?>
In the example above, it would make sense if we could match "John Doe," and not "JohnDoe." We can use the following regular expression to do so:
It's just as easy to search for a numerical string of characters:
<?php echo ereg("^[0-9]+$", "12345"); ?>
It's not only search patterns that can be grouped together. We can also group related search terms together using parentheses:
Because several characters are used to actually specify the grouping or syntax of a search pattern, such as the parentheses in (John|Jane), we need a way to tell the regular expression engine to ignore these characters and to process them as if they were part of the string being searched and not part of the search expression. The method we use to do this is called "character escaping" and involves propending any "special symbols" with a backslash. So, for example, if I wanted to include the or symbol '|' in my search, then I could do so like this: