PHP 几个常用的正则表达式

本文介绍了一组用于PHP的实用正则表达式,包括用户名、密码、电子邮件地址、手机号码、身份证号码、URL及图片标签等常见字段的验证规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录几个PHP中比较常用的正则。


/**
 * 验证用户名
 * 字母、数字、下划线、汉字组成,2-20位字符,不能为纯数字
 *
 * @param $username
 * @param int $min_len
 * @param int $max_len
 * @return bool|int
 */
public function isUserName($username, $min_len = 2, $max_len = 20)
{
    if (empty($username)) {
        return false;
    }
    $match = '/^(?![0-9]+$)[\w\x{4e00}-\x{9fa5}]{' . $min_len . ',' . $max_len . '}$/iu';
    return preg_match($match, $username);
}

 

 

/**
 * 验证密码格式
 * 6-20个英文字母、数字或符号,不能是纯数字
 *
 * @param $password
 * @param int $min_len
 * @param int $max_len
 * @return bool|int
 */
public static function isPassword($password, $min_len = 6, $max_len = 20)
{
    $match = '/^[\\~!@#$%^&*()-_=+|{}\[\],.?\/:;\'\"\d\w]{' . $min_len . ',' . $max_len . '}$/';
    $password = trim($password);
    if (empty($password)) {
        return false;
    }
    if (preg_match('/^[\d]*$/', $password)) {
        return false;
    }
    return preg_match($match, $password);
}

 




/**
 * 验证eamil格式
 * @param $email
 * @param string $match
 * @return bool|int
 */
public static function isEmail($email, $match = '/^[\w\d]+[\w\d-.]*@[\w\d-.]+\.[\w\d]{2,10}$/i')
{
    $email = trim($email);
    if (empty($email)) {
        return false;
    }
    return preg_match($match, $email);
}

 




/**
 * 验证手机号
 * @param $mobile
 * @param string $match
 * @return bool|int
 */
public static function isMobile($mobile, $match = '/^((\+86)?(1[3|4|5|6|7|8|9]\d{9}))$/')
{
    $mobile = trim($mobile);
    if (empty($mobile)) {
        return false;
    }
    return preg_match($match, $mobile);
}

 




/**
 * 验证身份证号码
 * @param $idcard
 * @param string $match
 * @return bool|int
 */
public static function isIdcard($idcard, $match = '/^\d{6}((1[89])|(2\d))\d{2}((0\d)|(1[0-2]))((3[01])|([0-2]\d))\d{3}(\d|X)$/i')
{
    $idcard = trim($idcard);
    if (empty($idcard)) {
        return false;
    } else if (strlen($idcard) > 18) {
        return false;
    }
    return preg_match($match, $idcard);
}

 

 

/**
 * 验证URL
 * @param $url
 * @param string $match
 * @return bool|int
 */
public static function isUrl($url, $match = '/^(http:\/\/)?(https:\/\/)?([\w\d-]+\.)+[\w-]+(\/[\d\w-.\/?%&=]*)?$/')
{
    $url = strtolower(trim($url));
    if (empty($url)) {
        return false;
    }
    return preg_match($match, $url);
}

 
//匹配html中的img标签
public static function matchImg($content)
{
    if (empty($content)) {
        return false;
    }
    $match = '/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i';
    return preg_match($match, $content);
}

转载于:https://www.cnblogs.com/kyuang/p/9675119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值