pre_match() 函数用来搜索匹配的字符串,原型如下:
[Plain Text] 纯文本查看 复制代码 int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
函数的第 1 个和第 2 个参数是必选参数。第 1 个参数 $pattern 是用户自定义的搜索正则表达式。第 2 个参数 $subject 是要搜索的字符串。也就是,我们在 $subject 中按照 $pattern 中的正则进行搜索。如果给出了第 3 个数组参数 $matches ,那么它就用来保存与第 1 个参数中的子模式(使用括号 "()" 括起来的模式单元)的各个部分的匹配结果。其中数组的第 1 个元素 matchs[0] 保存了与曾泽表达式 $pattern 匹配的整体内容,而 $mayches 中的其它元素,则按顺序依次保存了与正则表达式小括号内子表达式相匹配的内容。
如果函数找到匹配内容,返回值为真。由于 $flags 和 $offset 这两个参数不是很常用,这里就不展开了。
下面是示例代码:
[PHP] 纯文本查看 复制代码 <?php
$pattern = '/(https?|ftps?):\/\/(www)\.([^\.\/]+)\.(com|net|org|cn)(\/[\w-\.\/\?\%\&\=]*)?/i';
$subject = "欢迎阅读 http://www.groad.net/bbs/read.php?tid-7070.html 此篇帖子";
if (preg_match($pattern, $subject, $matches)) {
echo "$matches[0]"."<br>";
echo "$matches[1]"."<br>";
echo "$matches[2]"."<br>";
echo "$matches[3]"."<br>";
echo "$matches[4]"."<br>";
echo "$matches[5]"."<br>";
}
?>
运行输出:http://www.groad.net/bbs/read.php?tid-7070.html
http
www
groad
net
/bbs/read.php?tid-7070.html 上面的正则中有 5 个小括号,外加 1 个整体匹配,因此可知共有 6 个数组元素。 |