其实用了那么久,一想到使用正则,都是使用原生的字符串去使用正则。不知道原来PHP内部有那么多已经写好常用的正则函数,也真是惭愧,看来以后不能光闭门造车,还得多练习多看看外面的文章。
下面,就展示一个实战 – 写一个正则类demo:
class regexTool {
private $validate = array(
'require' => '/.+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', //邮箱
//url
'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
'currency' => '/^\d+(\.\d+)?$/', //金额
'number' => '/^\d+$/', //数字
'zip' => '/^\d{6}$/', //额。。。
'integer' => '/^[-\+]?\d+$/', //整数
'double' => '/^[-\+]?\d+(\.\d+)?$/', //双精度数字
'english' => '/^[A-Za-z]+$/', //英文
'qq' => '/^\d{5,11}$/', //QQ
'mobile' => '/^1(3|4|5|7|8)\d{9}$/', //手机号
);
private $returnMatchResult = false;
private $fixMode = null;
private $matches = array();
private $isMatch = false;
public function __construct($returnMatchResult = false, $fixMode = null) {
$this->returnMatchResult = $returnMatchResult;
$this->fixMode = $fixMode;
}
private function regex($pattern, $subject) {
if(array_key_exists(strtolower($pattern), $this->validate))
$pattern = $this->validate[$pattern].$this->fixMode;
$this->returnMatchResult ?
preg_match_all($pattern, $subject, $this->matches) :
$this->isMatch = preg_match($pattern, $subject) === 1;
return $this->getRegexResult();
}
private function getRegexResult() {
if($this->returnMatchResult) {
return $this->matches;
} else {
return $this->isMatch;
}
}
public function toggleReturnType($bool = null) {
if(empty($bool)) {
$this->returnMatchResult = !$this->returnMatchResult;
} else {
$this->returnMatchResult = is_bool($bool) ? $bool : (bool)$bool;
}
}
public function setFixMode($fixMode) {
$this->fixMode = $fixMode;
}
//检测是否为空
public function noEmpty($str) {
return $this->regex('require', $str);
}
//邮箱地址
public function isEmail($email) {
return $this->regex('email', $email);
}
//手机号码
public function isMobile($mobile) {
return $this->regex('mobile', $mobile);
}
public function check($pattern, $subject) {
return $this->regex($pattern, $subject);
}
//......
}最后推荐一个正则表达式工具 ,优点是可以实时调试正则匹配的效果: regexpal
没有难的技术,当你弄清它的原理时,你会发现原来如此简单~ 欢迎加群【195474288】讨论
