preg_match()
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。
语法:
1
|
int preg_match( string pattern, string subject [,
array
matches ] )
|
参数说明:
参数 | 说明 |
---|---|
pattern | 正则表达式 |
subject | 需要匹配检索的对象 |
matches | 可选,存储匹配结果的数组, $matches[0] 将包含与整个模式匹配的文本,$matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本,以此类推 |
例子 1:
1
2
3
4
5
6
7
8
9
|
<?php
if
(preg_match(
"/php/i"
,
"PHP is the web scripting language of choice."
,
$matches
))
{
print
"A match was found:"
.
$matches
[0];
}
else
{
print
"A match was not found."
;
}
|
输出:
1
|
A match was found:PHP
|
在该例子中,由于使用了 i 修正符,因此会不区分大小写去文本中匹配 php 。
注意:
preg_match() 第一次匹配成功后就会停止匹配,如果要实现全部结果的匹配,即搜索到subject结尾处,则需使用 preg_match_all() 函数。
例子 2 ,从一个 URL 中取得主机域名 :
1
2
3
4
5
6
7
8
|
<?php
// 从 URL 中取得主机名
preg_match(
"/^(http:\/\/)?([^\/]+)/i"
,
"http://blog.snsgou.com/index.php"
,
$matches
);
$host
=
$matches
[2];
// 从主机名中取得后面两段
preg_match(
"/[^\.\/]+\.[^\.\/]+$/"
,
$host
,
$matches
);
echo
"域名为:{$matches[0]}"
;
|
输出:
1
|
域名为:snsgou.com
|
preg_match_all()
preg_match_all() 函数用于进行正则表达式全局匹配,成功返回整个模式匹配的次数(可能为零),如果出错返回 FALSE 。
语法:
1
|
int preg_match_all( string pattern, string subject,
array
matches [, int flags ] )
|
参数说明:
参数 | 说明 |
---|---|
pattern | 正则表达式 |
subject | 需要匹配检索的对象 |
matches | 存储匹配结果的数组 |
flags | 可选,指定匹配结果放入 matches 中的顺序,可供选择的标记有:
|
下面的例子演示了将文本中所有 <pre></pre> 标签内的关键字(php)显示为红色。
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
$str
=
"<pre>学习php是一件快乐的事。</pre><pre>所有的phper需要共同努力!</pre>"
;
$kw
=
"php"
;
preg_match_all(
'/<pre>([\s\S]*?)<\/pre>/'
,
$str
,
$mat
);
for
(
$i
= 0;
$i
<
count
(
$mat
[0]);
$i
++)
{
$mat
[0][
$i
] =
$mat
[1][
$i
];
$mat
[0][
$i
] =
str_replace
(
$kw
,
'<span style="color:#ff0000">'
.
$kw
.
'</span>'
,
$mat
[0][
$i
]);
$str
=
str_replace
(
$mat
[1][
$i
],
$mat
[0][
$i
],
$str
);
}
echo
$str
;
?>
|
输出效果:
简化一下:
1
2
3
4
5
|
<?php
$str
=
"<pre>学习php是一件快乐的事。</pre><pre>所有的phper需要共同努力!</pre>"
;
preg_match_all(
'/<pre>([\s\S]*?)<\/pre>/'
,
$str
,
$matches
);
print_r(
$matches
);
?>
|
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
Array
(
[0] => Array
(
[0] => <pre>学习php是一件快乐的事。</pre>
[1] => <pre>所有的phper需要共同努力!</pre>
)
[1] => Array
(
[0] => 学习php是一件快乐的事。
[1] => 所有的phper需要共同努力!
)
)
|