PHP匹配Email、URL、IP

时间:2022-05-08 04:07:57
/*
* 正则表达式匹配
*/
$email = '137813369@qq.com';
$regex = '/\w+([−+.]\w+)*@\w+([−.]\w+)*\.\w+([−.]\w+)*/';
if (preg_match($regex, $email)) {
echo('匹配');
}else {
echo('不匹配');
} $url = 'http://www.cnblogs.com/hellohell/p/5718319.html';
$regex = '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?/';

$regex = '/^http(s?):\/\/[\w]+\.[\w]+[\S]*/'; 
if (preg_match($regex, $url)) {
echo('匹配');
}else {
echo('不匹配');
} $phone = '';
$regex = '/1[3458]\d{9}/';
if (preg_match($regex, $phone)) {
echo('匹配');
}else {
echo('不匹配');
} /*
* 自带函数匹配
*/
$email = "lastchiliarch@163.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo('匹配');
}else{
echo('不匹配');
} $url = "http://www.cnblogs.com/hellohell/p/5718319.htm";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo('匹配');
}else{
echo('不匹配');
} $ip = "123.54.178.71";
if (filter_var($ip, FILTER_VALIDATE_IP)) {
echo('匹配');
}else{
echo('不匹配');
}

如果要在文章中搜索匹配结果:

//查询匹配结果
$str = '手机号13712345678';
preg_match_all("/^1[34578]\d{9}$/", $str, $mobiles);
var_dump($mobiles);