首页> 基础笔记 >PHP基础学习 >PHP正则 PHP正则
PHP正则函数preg_match()笔录
作者:小萝卜 2019-08-21 【 PHP 正则 】 浏览 1768
简介函数preg_match() --执行一个正则表达式匹配int preg_match(string $pattern, string $subject[,array &$matches])搜索subject与pattern给定的正则表达式的一个匹配.
函数preg_match() --执行一个正则表达式匹配
int preg_match(string $pattern, string $subject[,array &$matches])
搜索subject与pattern给定的正则表达式的一个匹配.
实例:
<?php
//preg_match()函数实例
//一个用于匹配URL的正则表达式
$pattern = '/(https?|ftps?):\/\/(www)\.([^\.\/]+)\.(com|net|org)(\/[\w-\.\/\?\%\&\=]*)?/i';
//被搜索字符串
$subject = "网址为http://www.luowebs.com/index.php的位置是萝卜网络博客";
//使用preg_match()函数进行匹配
if(preg_match($pattern, $subject, $matches)) {
echo "搜索到的URL为:".$matches[0]."<br>"; //数组中第一个元素保存全部匹配结果
echo "URL中的协议为:".$matches[1]."<br>"; //数组中第二个元素保存第一个子表达式
echo "URL中的主机为:".$matches[2]."<br>"; //数组中第三个元素保存第二个子表达式
echo "URL中的域名为:".$matches[3]."<br>"; //数组中第四个元素保存第三个子表达式
echo "URL中的顶域为:".$matches[4]."<br>"; //数组中第五个元素保存第四个子表达式
echo "URL中的文件为:".$matches[5]."<br>"; //数组中第六个元素保存第五个子表达式
} else {
echo "搜索失败!"; //如果和正则表达式没有匹配成功则输出
}
?>
实例2--字符串的匹配:
//正则匹配函数:preg_match("正则表达式","被匹配字串
/*
[aoeiu] 表示任意一位元音字母
[0-9] 表示任意一位数字
[0-9][0-9] 表示任意两位数字
[^0-9] 表示任意一位非数字。
[0-9]{4} 表示4为连续任意数字
[a-z]{6,} 表示至少6位小写字母
[a-z]{6,8} 表示6至8位小写字母
[0-9]{1,} 至少1位数字 等价于 [0-9]+
[a-z]{0,} 任意位小写字母 等价于 [a-z]*
[a-z]{0,1} 可有可无的一位小写字母 等价于 [a-z]?
*/
//匹配字串中是否包含任意一位非 数字
if(preg_match("/[^0-9]/","3214,12341")){
echo "匹配!";
}else{
echo "不匹配!";
}
//匹配字串中是否包含任意两位数字
if(preg_match("/[0-9][0-9]/","s0ek78fc9gd4f")){
echo "匹配!";
}else{
echo "不匹配!";
}
//匹配字串中是否包含任意两位数字
if(preg_match("/[0-9][0-9]/","s0ek78fc9gd4f")){
echo "匹配!";
}else{
echo "不匹配!";
}
//匹配字串中是否包含任意一位数字
if(preg_match("/[0-9]/","sek7dfcgdf")){
//if(preg_match("/[0123456789]/","sek7dfcgdf")){
echo "匹配!";
}else{
echo "不匹配!";
}
//匹配字串中是否包含abc其中任意一个字符
if(preg_match("/[abc]/","sekdfcgdf")){
echo "匹配!";
}else{
echo "不匹配!";
}
实例3--数字的匹配:
/*
[1-9][0-9]* 正整数
-?[0-9]+ 整数
[1][345789][0-9]{9} 手机号码
[1-9][0-9]{5}[12][90][0-9]{2}[01][0-9][0-3][0-9]{4}[0-9xX] 身份证号码
/^-?\d+$|^-?0[xX][\da-fA-F]+$/
^-?[0-9]+$ 任意十进制整数
^-?0[xX][\da-fA-F]+$ 任意十六进制整数值
/^[0-9a-zA-Z_-]+@[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+){1,3}$/
zhangtao@lampbrother.net
*/
//精确匹配(绝对匹配)4位数字
if(preg_match("/^-?[0-9]+$/","30")){
echo "匹配!";
}else{
echo "不匹配!";
}
//精确匹配(绝对匹配)4位数字
if(preg_match("/^[0-9]{4}$/","4567")){
echo "匹配!";
}else{
echo "不匹配!";
}
//匹配字串中是否包含4到6位的数字
if(preg_match("/[0-9]{4,6}/","wqe12re3458wq567rd89fasd")){
echo "匹配!";
}else{
echo "不匹配!";
}
实例4:
<?php
header("Content-Type:text/html;charset=utf-8");
//正则的匹配查找
echo "<pre>";
//将字串中的两位数字匹配出来(此正则匹配函数只做一次匹配)
preg_match("/[0-9]{2}/","as56df78as69df",$a);
print_r($a);
//Array ( [0] => 56 )
//preg_match("/#.*#/","qe#rqw#erq#we",$a); //默认.*为最大匹配(贪婪匹配)
preg_match("/#.*?#/","qe#rqw#e#rsdq#we",$a); //默认.*?为最小匹配(拒绝贪婪匹配)
print_r($a);
很赞哦! (0)