您的位置:首页 > 编程语言 > PHP开发

php正则表达式—工具类的开发

2015-06-20 11:23 721 查看
<?php

class regexTool

{

private $validate = array(

'require' => '/.+/',

'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',

'url' => '/^((http|https|ftp):\/\/)?(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/',

'currency' => '/^\d+(\.\d+)?$/',

'number' => '/^\d+$/',

'zip' => '/^\d{6}$/',

'integer' => '/^[-\+]?\d+$/',

'double' => '/^[-\+]?\d+(\.\d+)?$/',

'english' => '/^[A-Za-z]+$/',

'qq' => '/^\d{5,11}$/',

'mobile' => '/^1(3|4|5|7|8)\d{9}$/',

);

private $returnMatchResult = false; // 是否返回匹配结果

private $fixMode = null; // 修正模式

private $matches = array(); // 匹配结果

private $isMatch = false; // 是否匹配到结果

function __construct($returnMatchResult = false,$fixMode = null)

{

$this->returnMatchResult = $returnMatchResult;

$this->fixMode = $fixMode;

}

/**

* 匹配目标字符串并返回结果

* @param string or array $pattern 匹配规则

* @param string or array $subject 目标字符串

*/

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();

}

/**

* 根据returnMatchResult成员判断返回何种结果类型并返回结果

*/

private function getRegexResult()

{

if($this->returnMatchResult)

{

return $this->matches;

}

else

{

return $this->isMatch;

}

}

/**

* 切换返回结果

* @param bool $bool 布尔值

*/

public function toggleReturnType($bool = null)

{

if(empty($bool))

{

$this->returnMatchResult = !$this->returnMatchResult;

}

else

{

$this->returnMatchResult = is_bool($bool) ? $bool : (bool)$bool;

}

}

/**

* 设置修正模式

@ param string $fixMode 修正模式

*/

public function setFixMode($fixMode)

{

$this->fixMode = $fixMode;

}

/**

* 检测是否为空

* @param string $str 目标字符串

*/

public function noEmpty($str)

{

return $this->regex('require',$str);

}

/**

* 检测是否为有效的email

* @param string $email 需要检测的email

*/

public function isEmail($email)

{

return $this->regex('email',$email);

}

/**

* 检测是否为手机号

* @param string $mobile 需要检测的手机号码

*/

public function isMobile($mobile)

{

$this->regex('mobile',$mobile);

}

/**

* 匹配目标字符串并返回结果

* @param string or array $pattern 匹配规则

* @param string or array $subject 目标字符串

*/

public function check($pattern,$subject)

{

return $this->regex($pattern,$subject);

}

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: