preg_match()和preg_match_all()

preg_match()返回pattern
的匹配次数。 它的值将是0次(不匹配)或1次,因为preg_match()在第一次匹配后 将会停止搜索。preg_match_all()不同于此,它会一直搜索subject直到到达结尾。 如果发生错误preg_match()返回 **FALSE
**
preg_match()
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。
语法:
int preg_match( string pattern, string subject [, array matches ] )

<?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.";
}
?>
A match was found: PHP

提示
preg_match() 第一次匹配成功后就会停止匹配,如果要实现全部结果的匹配,即搜索到subject结尾处,则需使用 preg_match_all() 函数。

<?php
// 从 URL 中取得主机名
preg_match("/^(http://)?([^/]+)/i","http://www.jb51.net/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^./]+\.[^./]+$/", $host, $matches);
echo "域名为:{$matches[0]}";
?>
域名为:jb51.net

preg_match_all()
preg_match_all() 函数用于进行正则表达式全局匹配,成功返回整个模式匹配的次数(可能为零),如果出错返回 FALSE 。
语法:
int preg_match_all( string pattern, string subject, array matches [, int flags ] )

<?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;
?>

正则匹配中文汉字
正则匹配中文汉字根据页面编码不同而略有区别:
•GBK/GB2312编码:[x80-xff>]+ 或 [xa1-xff]+
•UTF-8编码:[x{4e00}-x{9fa5}]+/u
例子:

<?php
$str = "学习php是一件快乐的事。";
preg_match_all("/[x80-xff]+/", $str, $match);
//UTF-8 使用:
//preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match);
print_r($match);
?>
Array
(
    [0] => Array
        (
            [0] => 学习
            [1] => 是一件快乐的事。
        )
)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于PCRE的介绍以及实现正则表达式功能的所有说明,都可以在官方手册中看到:正则表达式(兼容 Perl) 一、认识...
    拿破仑蛋糕阅读 1,625评论 0 1
  • PHP常用正则表达式汇总 正则表达式在 PHP 中的应用在 PHP 应用中,正则表达式主要用于: 正则匹配:根据正...
    DragonRat阅读 1,471评论 0 4
  • 概述 正则表达式是一种描述字符串结果的语法规则,是一个特定的格式化模式,可以匹配、替换、截取匹配的字符串。常用的语...
    醉于麦田阅读 515评论 0 0
  • 一、字符串操作 PHP开发中,我们遇到最多的可能就是字符串。 一个字符串 通过下面的3种方法来定义: 1、单引号 ...
    空谷悠阅读 792评论 1 6
  • 小时候我是哥哥的跟屁虫,形影不离,像狗皮膏药一样紧紧地粘在他身后。而哥哥则嫌我是他的累赘,他和他的伙伴们像地...
    大江東去去阅读 819评论 0 0