If you constantly create different functions to check or manipulate part of a string, you may have to discard all these functions and replace them with regular expressions. If you answer "yes" to any of the following questions, you must consider using a regular expression:
Are you writing some custom functions to check form data (for example, one @ and one point in the email address )?
Do you want to write custom functions to cycle every character in a string? If this character matches a specific feature (for example, it is capitalized or it is a space ), then replace it?
In addition to the uncomfortable string check and operation methods, if you do not write code efficiently, the above two will also slow your program down. Do you prefer to use the following code to check an email address:
<? PHP
Function validateemail ($ email)
{
$ Hasatsymbol = strpos ($ email ,"@");
$ Hasdot = strpos ($ email ,".");
If ($ hasatsymbol & $ hasdot)
Return true;
Else
Return false;
}
Echo validateemail ("mitchell@devarticles.com ");
?>
... Or use the following code:
<? PHP
Function validateemail ($ email)
{
Return ereg ("^ [A-Za-Z] + @ [A-Za-Z] +/. [A-Za-Z] + $", $ email );
}
Echo validateemail ("mitchell@devarticles.com ");
?>
Certainly, the first function is relatively easy and looks good in structure. But isn't it easier to use the email address check function of the next version?
The second function shown above only uses regular expressions, including a call to the ereg function. The ereg function returns true or false to declare whether its string parameter matches the regular expression.
Many programmers avoid Regular Expressions because they (in some cases) are slower than other text processing methods. Regular expressions may be slow because they involve copying and pasting strings in memory, because each new part of the regular expression matches a string. However, in my experience with regular expressions, unless you run a complex Regular Expression on hundreds of lines in the text, the performance defects are negligible, this is also rare when you use a regular expression as the input data check tool.
Regular expression syntax
Before you can match a string to a regular expression, you must first create a regular expression. At the beginning, the regular expression syntax was a bit odd. Each phrase in the expression represents a type of search feature. The following are some of the most common regular expressions that correspond to an example of how to use them:
String Header
Search for the header of a string using ^, such
<? PHP echo ereg ("^ hello", "Hello world! ");?>
Returns true,
<? PHP echo ereg ("^ hello", "I say hello World");?>
False is returned because hello is not in the header of the string "I say hello World.
End of string
Search the end of a string with $, for example:
<? PHP echo ereg ("bye $", "goodbye");?>
Returns true,
<? PHP echo ereg ("bye $", "Goodbye my friend");?>
Returns false because bye is not at the end of the string "Goodbye my friend.
Any single character
Search for any character and use a vertex (.), for example:
<? PHP echo ereg (".", "cat");?>
Returns true,
<? PHP echo ereg (".", "") ;?>
Returns false because the string to be searched does not contain any character. You can use curly brackets to tell the Regular Expression Engine how many individual characters it will match. If I only want to match five characters, I can use ereg as follows:
<? PHP echo ereg (". {5 }$", "12345");?>
The code above tells the Regular Expression Engine to return true if at least five consecutive characters appear at the end of the string. We can also limit the number of consecutive characters:
<? PHP echo ereg ("A {1, 3} $", "AAA");?>
In the above example, we have told the Regular Expression Engine that our search string matches the expression. It must have between 1 and 3 "A" characters at the end.
<? PHP echo ereg ("A {1, 3} $", "aaab");?>
The above example will not return true. Although there are three "A" characters in the search string, they are not at the end of the string. If we remove the ending string matching $ from the regular expression, this string is matched.
We can also tell the Regular Expression Engine to match at least a certain number of characters in a row. If they exist, they can match more. We can do this:
<? PHP echo ereg ("A {3, }$", "aaaa");?>
Zero or multiple repeated characters
To tell the Regular Expression Engine that a character may exist or can be repeated, we use the * character. Both examples here return true.
<? PHP echo ereg ("T *", "Tom");?>
<? PHP echo ereg ("T *", "fom");?>
Even if the second example does not contain the character "T", the system returns true because * indicates that the character can appear but is not required. In fact, any common string mode will make the preceding ereg call return true, because the 'T' character is optional.
One or more repeated characters
To tell the Regular Expression Engine that a character must exist or can be repeated more than once, we use + characters, such
<? PHP echo ereg ("Z +", "I like the zoo");?>
The following example also returns true:
<? PHP echo ereg ("Z +", "I like the zzzzzzzzoo! ");?>
Zero or duplicate characters
We can also tell the Regular Expression Engine that a character must exist only once or not. We use? Character to do this job, just like
<? PHP echo ereg ("C? "," Cats are fuzzy ");?>
If we want to, we can completely delete 'c' from the search string above. This expression will still return true .'? 'Indicates that a 'C' can appear anywhere in the search string, but it is not required.
Regular expression syntax (continued)
Space Character
To match spaces in a search string, we use the pre-defined POSIX class [[: Space]. square brackets indicate the relevance of consecutive characters. ": Space:" indicates the class to be matched (in this case, it is any blank character ). White spaces include TAB characters, new line characters, and blank characters. Alternatively, if the search string must contain only one space, rather than a tab or a new line character, you can use a space character (""). In most cases, I tend to use ": Space:", because it means that my intention is not just a single space character, which is easily ignored. Here are some POSIX-standard pre-defined classes,
There are some POSIX-standard pre-defined classes that can be used as regular expressions, including [: alnum:], [: digit:], [: lower:], and so on. The complete list can be viewed here
We can match a single blank character like this:
<? PHP echo ereg ("Mitchell [[: Space:] Harper", "Mitchell Harper");?>
We can also use? To tell the Regular Expression Engine that there is no blank or blank matching.
<? PHP echo ereg ("Mitchell [[: Space:]? Harper "," mitchellharper ");?>
Mode group
The related patterns can be separated in square brackets. It is easy to use [A-Z] and [A-Z] to specify that only one lower-case letter or one column of upper-case letters exist in part of the search string.
<? PHP
// Lowercase letters are required from the first to the last
Echo ereg ("^ [A-Z] + $", "johndoe"); // return true
?>
Or Image
<? PHP
// The first and last are uppercase letters.
Ereg ("^ [A-Z] + $", "johndoe"); // returns true?
?>
We can also tell the Regular Expression Engine that we want to use either lower-case letters or upper-case letters. We just need to combine the [A-Z] and [A-Z] patterns.
<? PHP echo ereg ("^ [A-Za-Z] + $", "johndoe");?>
In the above example, if we can match "John Doe" instead of "johndoe", it will be very meaningful. We use the following regular expression to do this:
^ [A-Za-Z] + [[: Space:] {1} [A-Za-Z] + $
It is easy to search for a numeric string
<? PHP echo ereg ("^ [0-9] + $", "12345");?>
Word grouping
Not only can the search mode be grouped, but we can also use parentheses to group related search words.
<? PHP echo ereg ("^ (John | Jane). + $", "John Doe");?>
In the above example, we have a string header character followed by "John" or "Jane", at least one other character, and then a string tail character. So...
<? PHP echo ereg ("^ (John | Jane). + $", "Jane Doe");?>
... Will also match our search mode
Special characters
Because some characters are used in a clear grouping or syntax in the search mode, such as parentheses in (John | Jane), we need to tell the Regular Expression Engine to block these characters, process them to make them part of the searched string, not part of the search expression. The method we use is called "character escape", which involves adding a backslash to any "special symbol. So, for example, if I want to include '|' in my search, I can do this.
<? PHP echo ereg ("^ [A-Za-Z] +/| [A-Za-Z] + $", "John | Jane");?>
Here are only a few characters you want to escape. You must escape ^, $, (,),., [, | ,*,?, +,/And {.
I hope you will feel a little bit more powerful about regular expressions. Now let's look at two examples of checking a string in data using a regular expression.
Regular Expression example
Example 1
Let's make the first example quite simple. Check a standard URL. A standard URL (without a port number) consists of three parts:
[Protocol]: // [domain name]
Let's start from the Protocol part that matches the URL and make it only use HTTP or FTP. We can use the following regular expression to do this:
^ (HTTP | FTP)
^ Character refers to the header of a string. It enclose HTTP and FTP with parentheses and separate them with the "or" symbol (|, we tell the Regular Expression Engine that either HTTP or FTP must start with a string.
A domain name is usually composed of www.somesite.com, but you can select the WWW part at will. For the sake of simplicity, we only allow. com,. net, and. org domain names to be considered. We 'd better represent the domain name in the regular expression as follows:
(WWW /.)?. +/. (COM | net | org) $
When we put everything together, our regular expression can be used to check a domain name, such:
<? PHP
Function isvaliddomain ($ domainname)
{
Return ereg ("^ (HTTP | FTP): // (www /.)?. +/. (COM | net | org) $ ", $ domainname );
}
// True (true)
Echo isvaliddomain ("http://www.somesite.com ");
// True (true)
Echo isvaliddomain ("ftp://somesite.com ");
// False)
Echo isvaliddomain ("ftp://www.somesite.fr ");
// False)
Echo isvaliddomain ("www.somesite.com ");
?>
Example 2
Because I live in Sydney, Australia, let's check a typical Australian international phone number. The format of the Australian international phone number is as follows:
+ 61x XXXX-xxxx
The first X is the area code, and the others are telephone numbers. Check the phone number that starts with '+ 61' and follows a zone number between 2 and 9. We use the following regular expression:
^/+ 61 [2-9] [[: Space:]
Note: In the search mode above, the '+' character is escaped with '', so that it can be included in the search without being interpreted as a regular expression. [2-9] tells the Regular Expression Engine that we need to include a number between 2 and 9. [[: Space:] indicates that the regular expression is expected to have a blank space.
Here is the remaining search mode for phone numbers:
[0-9] {4}-[0-9] {4} $
There is nothing unusual here. We just tell the Regular Expression Engine the number available for the phone number. It must be a combination of four numbers followed by a connector, followed by a combination of four other numbers, and then a string's tail character.
Put the complete regular expression together and put it into a function. We can use the code to check some Australian international phone numbers:
<? PHP
Function isvalidphone ($ phonenum)
{
Echo ereg ("^/+ 61 [2-9] [[: Space:] [0-9] {4}-[0-9] {4} $ ", $ phonenum );
}
// True (true)
Echo isvalidphone ("+ 619 0000-0000 ");
// False)
Echo isvalidphone ("+ 60 00000000 ");
// False)
Echo isvalidphone ("+ 611 00000000 ");
?>