PHP Preg_Match 问题
Issue with PHP Preg_Match
我正在开发一个 CodeIgniter 项目,我正在进行自定义验证,但我不是正则表达式专家。
到目前为止,我已经做了一个简单的测试,但我似乎无法做到这一点。
此验证只能包含 A-Z a-z 0-9 和特殊字符如:
@ ! # / $ % & ' * + - = ? ^ _ ` { | } ~ .
我不能( ) [ ] : ; " < > , \
在我的控制器中:
public function test(){
$this->form_validation->set_rules('communication_number', 'Communication Number', 'required|trim|xss_clean|callback_validate_communication_number');
$this->form_validation->set_message("validate_communication_number", "The %s field must only contain blah blah");
if($this->form_validation->run() == false)
{
echo validation_errors();
}
else
{
echo "Passed";
}
}
public function validate_communication_number($communication_number)
{
if(preg_match("/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i", $communication_number))
{
return true;
}
else
{
return false;
}
}
如果您使用双引号或仅更改为单引号,则必须使用 \
转义反斜杠:
if(preg_match('/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i', $ff_communication_room))
^--- Here
但是,您可以这样编写正则表达式(您不需要所有那些转义的反斜杠:
^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$
如您所见,这是一个有效的正则表达式:
代码
$re = '/^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$/i'; // Note hyphen at the end
$str = "your string";
if(preg_match($re, $str))
{
return true;
}
else
{
return false;
}
我正在开发一个 CodeIgniter 项目,我正在进行自定义验证,但我不是正则表达式专家。 到目前为止,我已经做了一个简单的测试,但我似乎无法做到这一点。 此验证只能包含 A-Z a-z 0-9 和特殊字符如:
@ ! # / $ % & ' * + - = ? ^ _ ` { | } ~ .
我不能( ) [ ] : ; " < > , \
在我的控制器中:
public function test(){
$this->form_validation->set_rules('communication_number', 'Communication Number', 'required|trim|xss_clean|callback_validate_communication_number');
$this->form_validation->set_message("validate_communication_number", "The %s field must only contain blah blah");
if($this->form_validation->run() == false)
{
echo validation_errors();
}
else
{
echo "Passed";
}
}
public function validate_communication_number($communication_number)
{
if(preg_match("/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i", $communication_number))
{
return true;
}
else
{
return false;
}
}
如果您使用双引号或仅更改为单引号,则必须使用 \
转义反斜杠:
if(preg_match('/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i', $ff_communication_room))
^--- Here
但是,您可以这样编写正则表达式(您不需要所有那些转义的反斜杠:
^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$
如您所见,这是一个有效的正则表达式:
代码
$re = '/^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$/i'; // Note hyphen at the end
$str = "your string";
if(preg_match($re, $str))
{
return true;
}
else
{
return false;
}