preg_match(PHP 3 >= 3.0.9, PHP 4, PHP 5)preg_match — 进行正则表达式匹配。并且只匹配一次,注意与preg_match_all区别。
函数用法
int preg_match_all ( string pattern, string subject, array matches, [int flags] )
返回值
preg_match()返回pattern的匹配次数。 它的值将是0次(不匹配)或1次,因为preg_match()在第一次匹配后 将会停止搜索。preg_match_all()不同于此,它会一直搜索subject直到到达结尾。 如果发生错误preg_match()返回 FALSE。
范例
#1 查找文本字符串”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.";
}
?>
0
1
2
3
4
5
6
7
//模式分隔符后的"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.";
}
?>
#2 查找单词”word”
/* 模式中的\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.";
}
?>
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 模式中的\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.";
}
?>
#3 获取URL中的域名
//从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";
?>
0
1
2
3
4
5
6
7
8
9
//从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
#4 使用命名子组
$str = 'foobar: 2008';
preg_match('/(?P\w+): (?P\d+)/', $str, $matches);
/* 下面例子在php 5.2.2(pcre 7.0)或更新版本下工作, 然而, 为了后向兼容, 上面的方式是推荐写法. */
// preg_match('/(?\w+): (?\d+)/', $str, $matches);
print_r($matches);
?>
0
1
2
3
4
5
6
7
8
9
10
11
$str='foobar: 2008';
preg_match('/(?P\w+): (?P\d+)/',$str,$matches);
/* 下面例子在php 5.2.2(pcre 7.0)或更新版本下工作, 然而, 为了后向兼容, 上面的方式是推荐写法. */
// preg_match('/(?\w+): (?\d+)/', $str, $matches);
print_r($matches);
?>
以上例程会输出:
Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)
注释
如果你仅仅想要检查一个字符串是否包含另外一个字符串,不要使用preg_match()。 使用strpos()或strstr()替代完成工作会更快。