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

后端开发   发布日期:2023年05月19日   浏览次数:198

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

以上就是PHP中preg_match()和preg_match_all()正则表达式的用法区别的详细内容,更多关于PHP中preg_match()和preg_match_all()正则表达式的用法区别的资料请关注九品源码其它相关文章!