(PHP 4, PHP 5)
preg_match — 执行一个正则表达式匹配
$pattern
   , string $subject
   [, array &$matches
   [, int $flags = 0
   [, int $offset = 0
  ]]] )
  搜索subject与pattern给定的正则表达式的一个匹配.
  
pattern
     要搜索的模式, 字符串类型.
subject
     输入字符串.
matches
     
      如果提供了参数matches, 它讲被填充为搜索结果.
      $matches[0]将包含完整模式匹配到的文本, $matches[1]
      将包含第一个捕获子组匹配到的文本, 以此类推.
      
flags
     
       flags可以被设置为以下标记值:
       
PREG_OFFSET_CAPTURE
         matches参数的数组, 使其每个元素成为一个由
          第0个元素是匹配到的字符串, 第1个元素是该匹配字符串
          在目标字符串subject中的偏移量.
          
         offset
     
      通常, 搜索从目标字符串的开始未知开始.可选参数offset用于
      指定从目标字符串的某个未知开始搜索(单位是字节).
      
Note:
使用
offset参数不同于向 preg_match() 传递按照位置通过substr($subject, $offset)截取目标字符串结果, 因为pattern可以包含断言比如^, $ 或者(?<=x). 比较:<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>以上例程会输出:
Array ( )当这个示例使用截取后传递时
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>将会产生匹配
Array ( [0] => Array ( [0] => def [1] => 0 ) )
   preg_match()返回pattern的匹配次数.
  它的值将是0次(不匹配)或1次, 因为 preg_match()在第一次匹配后
  将会停止搜索. preg_match_all()不同于此, 它会一直搜索subject
  直到到达结尾.
   如果发生错误 preg_match()返回FALSE.
  
| 版本 | 说明 | 
|---|---|
| 5.2.2 | 命名子组可以接受(?<name>), (?'name') 以及(?P<name>)语法. 之前版本仅接受(?P<name>)语法. | 
| 4.3.3 | 
        增加了参数offset.
        | 
      
| 4.3.0 | 
        增加了标记PREG_OFFSET_CAPTURE.
        | 
      
| 4.3.0 | 
        增加了参数flags.
        | 
      
Example #1 查找文本字符串"php"
<?php
//模式分隔符后的"i"标记这是一个大小写不敏感的搜索
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>
Example #2 查找单词"word"
<?php
/* 模式中的\b标记一个单词边界, 所以只有独立的单词"web"会被匹配, 而不会匹配
 * 单词的部分内容比如"webbing" 或 "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>
Example #3 获取URL中的域名
<?php
//从URL中获取主机名称
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];
//获取主机名称的后面两部分
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
以上例程会输出:
domain name is: php.net
Example #4 使用命名子组
<?php
$str = 'foobar: 2008';
preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
/* 下面例子在php 5.2.2(pcre 7.0)或更新版本下工作, 然而, 为了后向兼容, 上面的方式是推荐写法. */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);
print_r($matches);
?>
以上例程会输出:
Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)