(PHP3 >= 3.0.9, PHP4 )
preg_match -- Perform a regular expression match
Description
int preg_match
(string pattern, string subject [, array
matches])
Searches subject for a match to the regular
expression given in pattern.
If matches is provided, then it is filled
with the results of search. $matches[0] will contain the text that
match the full pattern, $matches[1] will have the text that matched
the first captured parenthesized subpattern, and so on.
Returns true if a match for pattern was
found in the subject string, or false if not match was found
or an error occurred.
Példa 1. find the string of text "php" 1
2 // the "i" after the pattern delimiter indicates a case-insensitive search
3 if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
4 print "A match was found.";
5 } else {
6 print "A match was not found.";
7 }
8 |
|
Példa 2. find the word "web" 1
2 // the \b in the pattern indicates a word boundary, so only the distinct
3 // word "web" is matched, and not a word partial like "webbing" or "cobweb"
4 if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
5 print "A match was found.";
6 } else {
7 print "A match was not found.";
8 }
9 if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
10 print "A match was found.";
11 } else {
12 print "A match was not found.";
13 }
14 |
|
Példa 3. Getting the domain name out of a URL 1
2 preg_match("/^(.*)([^\.]+\.[^\.]+)(\/.*)?/U",
3 "http://www.php.net/index.html", $matches);
4 // show the second parenthesized subpattern
5 echo "domain name is: ".$matches[2]."\n";
6 |
|
This example will produce:
1
2 domain name is: php.net
3 |
See also
preg_match_all(),
preg_replace(), and
preg_split().