| The code is as follows: |
Copy code |
<? Php // The "I" after the pattern delimiter indicates a search that is case-insensitive. If (preg_match ("/php/I", "PHP is the web scripting language of choice .")){ Print "A match was found ."; } Else { Print "A match was not found ."; } ?> |
Get current time
| The code is as follows: |
Copy code |
<? Php // The string to be matched. The date function returns the current time. "Current Time: am" $ Content = "Current time:". date ("Y-m-d h: I "); // Match the date and time. If (preg_match ("/d {4}-d {2}-d {2} d {2}: d {2} [ap] m/", $ content, $ m )) { Echo "the matching time is:". $ m [0]. "n"; // "am" } // Obtain the date and time respectively. If (preg_match ("/([d-] {10}) ([d:] {5} [ap] m)/", $ content, $ m )) { Echo "current date:". $ m [1]. "n"; // "2012-04-20" Echo "the current time is:". $ m [2]. "n"; // "07:31 am" } ?> |
This example verifies that the Email address is in the correct format. Now let's take a look at the various rules represented by this regular expression.
Get Google homepage title
For example, to obtain the title of the google homepage, the code is as follows:
| The code is as follows: |
Copy code |
<? Php $ Str = file_get_contents ('http: // www.google.com '); Preg_match ('/<title> (. *) </title>/', $ str, $ arr ); Echo $ arr [1]; ?> |
Retrieve domain name from website
| The code is as follows: |
Copy code |
<? Php Preg_match ("/^ (http ://)? ([^/] +)/I "," http://www.111cn.net/index.html ", $ matches ); $ Host = $ matches [2]; // Obtain the last two segments from the host name Preg_match ("/[^./] +. [^./] + $/", $ host, $ matches ); Echo "domain name is: {$ matches [0]} n "; ?> |
Preg_match ($ pattern, $ string, $ matcher) where $ pattern corresponds to/^ (http ://)? ([^/] +)/I, $ string is http://www.php.net/index.html,$matchis the matching result.
If matches is provided, it is filled with the search results. $ Matches [0] will contain the text that matches the entire pattern, $ matches [1] will contain the text that matches the child pattern in the first captured bracket, and so on.
$ Matches [0] will contain the text that matches the entire pattern. We use pring_r to print the first $ matches:
| The code is as follows: |
Copy code |
Array ( Http://www.111cn.net [1] => http :// [2] => www.111cn.net) |
$ Matches [0] will contain the text that matches the entire pattern, and $ matches [1] will contain the text that matches the child pattern in the first captured parentheses. In the regular expression, () indicates the pattern: Match pattern and obtain this match. The obtained match can be obtained from the generated Matches set. The SubMatches set is used in VBScript, and $0… is used in JScript... $9 attribute. That is to say, the value marked as 1 in the array is/^ (http: //) in the regular expression ://)? ([^/] +)/I value in the first! The value of array subscript 2 is similar.