regex - Issue with PHP Preg_Match -


i'm working on codeigniter project, , i'm making custom validation, , i'm no regex expert. far, have made simple test, cannot seem right. validation can contain a-z a-z 0-9 , special characters such as:

@ ! # / $ % & ' * + - = ? ^ _ ` { | } ~ . 

i cannot have ( ) [ ] : ; " < > , \

in controller:

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 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;     } } 

you have escape backslashes using \\ if use double quotes or change single quote this:

if(preg_match('/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i', $ff_communication_room))               ^--- here 

however, can write regex (you don't need escaped backslashes:

^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$ 

as can see, it's valid regex: regular expression visualization

working demo

code

$re = '/^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$/i'; // note hyphen @ end $str = "your string";   if(preg_match($re, $str)) {     return true; } else {     return false; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -