欢迎您来到,李雷博客 | PHP博客        登录  |  注册

PHP中preg_match()和preg_match_all()正则表达式的用法区别

更新:2023-02-10 08:09:31
人气:470
来源:金星show
A+

preg_match_all:从左边开始一直到尾部,找出所有匹配的字符串。匹配结果$matches为二维数组,$matches[0]是匹配到的完整结果,$matches[1]是匹配到完整结果的字组。

preg_match:从左边开始,匹配到第一个符合字符串后停止匹配。匹配结果$matches为一维数组,$matches[0]是匹配到的完整结果,$matches[1]是匹配到完整结果的字组。

语法: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","https://www.mdaima.com/jingyan/", $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 ] )

$get_htm_hello='<div class="information-details-msg">
                    <span class="send-time">发布时间:<span>2023-02-09 09:17:17</span></span>
                    <span class="comefrom">来源:<span>李雷博客</span></span>
                    <span class="readmath">阅读:<span id="reading_quantity">5899</span></span>
                    <span class="send-time">发布时间:<span>2023-02-10 09:17:17</span></span>
                    <span class="special">栏目:<a style="color:#9EA7B3;" href="https://www.mdaima.com"><span>PHP博客</span></a></span>';


$fabutime_regex_1 =  '/发布时间:<span>.*<\/span><\/span>/i';
preg_match_all($fabutime_regex_1, $get_htm_hello, $fabutime_array);
$fabutime = $fabutime_array[0];
$fabutime = str_replace('发布时间:<span>', '', $fabutime);
$fabutime = str_replace('</span></span>', '', $fabutime);

print_r($fabutime);
echo $fabutime[0];
exit;

正则匹配中文汉字正则匹配中文汉字根据页面编码不同而略有区别:

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] => 是一件快乐的事。
        )
)

 

 

推荐的文章
# 发表我的评论
  /     /  
# 最近评论
暂时还没有评论,要不要说点什么?
  Ads by Google
  联系博主
Hello,本博客系统采用PHP和MySql开发,程序开发完全是因为个人爱好,是自己纯手写PHP源代码,未采用任何PHP框架!
QQ:858353007   微信号:lileihot123
网站地图
会员服务
关于我们
QQ:858353007
 
广告服务
加我微信
移动端访问
 
 
Copyright © 2014- 2024 www.mdaima.com All Rights Reserved.
李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4