记录几个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);
}