preg_match
(PHP 3>= 3.0.9, PHP 4 )preg_match -- Perform a regular expression match
Description
int preg_match ( string pattern, string subject [, array matches [, int flags]])
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 matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. flags can be the following flag: 
PREG_OFFSET_CAPTURE
If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 . The flags parameter is available since PHP 4.3.0 . preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occured. Example 1. Find the string of text "php"// the "i" after the pattern delimiter indicates a case-insensitive search
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.";
}
 
 
Example 2. find the word "web"// the \b in the pattern indicates a word boundary, so only the distinct
// word "web" is matched, and not a word partial like "webbing" or "cobweb"
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}
 
 
Example 3. Getting the domain name out of a URL// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/",$host,$matches);
echo "domain name is: ".$matches[0]."\n";
 This example will produce: domain name is: php.net
  
See also preg_match_all(), preg_replace(), and preg_split(). User Contributed Notes
preg_match   
[email protected]
12-Mar-2000 02:23 
 
If you want to use some of PHP's special characters in your expression,
such as $, you must escape it twice. For example:$matchme = "\$example";
if (preg_match("/\$example/", $matchme)) {will not be matched because PHP interprets the \$ and passes it as $.
Instead, you must do this:if (preg_match("/\\\$example/", $matchme)) { 
 
[email protected]
13-Jun-2001 11:34 
 
See also ereg_match() for POSIX style. If you don't need regular
expressions, use strstr() or strpos() instead. 
 
[email protected]
18-Jan-2002 12:36 
 
To split a host, you can use this expresion. preg_match("/^(.*:\/\/)?([^:\/]+):?([0-9]+)?(.*)/", $url,
$match);
list(,$proto,$host,$port,$file) = $match;
 
Meaning: starts with, possibly, one or more letters, followed by
"://" (protocol), one or more letters, but a colon (host),
possibly a colon, followed by the posibility of one or more numbers
(port), and any number of trailing chars, (file/query). 
 
[email protected]
08-Feb-2002 05:12 
 
Quick Note to ease Perl to PHP Translation. preg_match that return an array....
that can be directly sent into a list($r1, $r2, $r3)function preg_match_array( $pattern, $stringtoregex ) {
        // To Ease Translation from Perl to PHP
        // In Perl We Use Often ( $a, $b, $c) = ( $stringtoregex ~= 
        //               /^(...) (...) (...)$/ );
        // Translate this into PHP Code like this
        //    list( $a, $b, $c) = preg_grep_array( 
        //             "/^(...) (...) (...)$/",
        //             $stringtoregex);
        $retarray=array();
        preg_match( $pattern, $stringtoregex, $retarray);        // Destroy index zero which is the whole string
        unset( $retarray[0]);   
        return $retarray;

 
[email protected]
16-Apr-2002 12:37 
 
It is possible to do negative lookbehinds with PCRE (perl 5+), but only
fixed length.preg_match('/(?<!AB)C/',$foo,$match);This will match 'C' only if NOT preceeded by 'AB'. 'AB' must be a fixed
length string, it cannot be an expression. 
 
simon at blueshell.dk
10-Jun-2002 06:57 
 
To avoid the double escaping you can also just use single quotes, only it
prevents from inserting variable data since '$foo' is interpreted as
string $foo and not variable $foo.preg_match('/^[$oi]$/', $foo, $matches);Won't look for variable $oi but one of the three characters $, o or i.-- 
Simon 
 
http://www.ravis.org/
16-Jul-2002 05:14 
 
Here's an expression that breaks apart any standard URI/URL into all it's
various components (including username/password and query string)...preg_match("/^((.*?):\/\/)?(([^:]*):([^@]*)@)?([^\/:]*)
            (:([^\/]*))?([^\?]*\/?)?(\?(.*))?$/",$URI,$Components);
list(,,$Protocol,,$Username,$Password,$Host,,$Port,$Path,,$Query) =
$Components;Breakdown:
expected format is in 'single quotes'
examples (eg:) are examples of what would be returned by the above
expression^
Start of line((.*?):\/\/)?
Possibly a protocol ('protocol://' - eg: "http")(([^:]*):([^@]*)@)? 
Possibly a username password combo ('username:password@' - eg:
"jsmith" and "birthday")([^\/:]*) 
A host or IP ('host:' or 'host/' - eg: "your.server.com")(:([^\/]*))? 
Possibly a port (':port/' - eg: "80")([^\?]*\/?)?
Possibly a path, possibly with a trailing slash ('/path/to/file' or
'/path/to/dir/' - eg "/path/to/file.zip")(\?(.*))? 
Possibly a query string ('?query' - eg: "var1=val&var2=val")$ 
End of lineSo we have: (optionals are in {braces})
{protocol://}{username:password@}host{:port}{/path}{?query}No checks are done for "proper" formatting (eg: ports are digits
only). You can implement your own checks if you like. I prefer to break
apart the URI first and don't worry about what's there (at least at this
stage). Also be careful with $Protocol, as it could be mixed case (http,
HTTP, or hTtP) - you should do something like a strtolower() on it before
working with it. Naturally make sure the entire preg_match expression is
on one line (and not split like shown here).
另外在本版有类似的帖子,搜索一下