PHP中preg_match()和preg_match_all()正则表达式的用法区别
更新:2023-02-10 08:09:31
人气:746
来源:金星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] => 是一件快乐的事。
)
)
推荐的文章
随手记
- ● 统信UOS开机指定网址全屏启动自带浏览器以及屏蔽ALT+F4关闭
- ● xshellSSH连接Linux服务器防止超时退出
- ● php8开启OpenSSL扩展库报错disabledinstallext
- ● 统信系统linux安装php时的报错libxml-2.0>=2.7.6
- ● tidb关闭sql_mode=ONLY_FULL_GROUP_BY模式
- ● windows10如何开机自动运行bat文件
- ● Win10Mysql8初始密码丢失,初始化又不显示密码
- ● UOS系统关闭防火墙或者放行tcp80端口
- ● 统信系统UOS纯命令行与图形模式界面桌面切换方法
- ● javascript(js)的小数点乘法除法问题详解
PHP经验分享
- ● PHP代码用UDP方式远程唤醒电脑让计算机开机
- ● apache下php生成验证码图片不能显示
- ● PHP使用AES加密解密示例(无偏移)
- ● Pluginmysql_native_passwordreported:''mysql_native_password'isdeprecate问题
- ● PHP实现计算CRC-16/MODBUS校验位
- ● MySQLSUM在没有符合查询条件时返回结果为空的处理办法
- ● 如何开启PHP8的JIT提升运行速度
- ● 钉钉API接口-用PHP+Curl实现获取用户信息
- ● 钉钉API接口-用PHP+Curl实现获取应用Access_Token
- ● 在PHP中使用CURL,“撩”服务器只需几行——phpcurl详细解析和常见大坑