Home > database >  How to allow "@", slash and underscore in the regex expression
How to allow "@", slash and underscore in the regex expression

Time:06-27

Im new to this. Can anyone help me with a regex expression. I need a regex expression which is allowing following characters [a-zA-Z0-9.?@/_-] but not others. Unfortunately only this is working [a-zA-Z0-9.?-]. Underscore, at sign - @ and slash (even if I escpe it /) are ignored.

php

 private $message_empt = "Field cant not be empty";
     private $message_err = "Nothing found";
     private $message_spchar = "No sepcial chars allowed";
     private $pregArg = '[a-zA-Z0-9.?@/_-]'; 
     
     public function __construct($sent_data) {
    
        $this->data = trim($sent_data); // Remove white spaces !!!
    
     }
     
     public function valDataset() { 
        
        $verif_funct = preg_match($this->pregArg, $this->data);
        
        if ($this->data == "") {
        
            echo "<div class='h2 text-danger'>" . $this->message_empt . "</div>";
            die();
        
        }
        
        elseif ($verif_funct == 1) {
            
            echo "<div class='h2 text-danger'>" . $this->message_spchar . "</div>";
            die();
            
        }
        
     }
 
 }

CodePudding user response:

Your regex is only looking for one character in the set; you need to add the quantifier for one or more or zero or more * if you allow empty values. Your regex is also looking for that character to occur anywhere in the string; you need to use the anchors for the start ^ and end $ of the string.
It should look something like this:

     private $pregArg = '/^[a-zA-Z0-9.?@/_-] $/'; 

CodePudding user response:

This is how you do it in javascript:

const str1 = 'abcABC012.?@/_-';
const str2 = '&é"(§è!çà)';
const regex = /[a-zA-Z0-9.?@/_-] /;
console.log(regex.test(str1));
// expected output: true
console.log(regex.test(str2));
// expected output: false

This is how you do it in php:

$str1 = 'abcABC012.?@/_-';
$str2 = '&é"(§è!çà)';
$regex = '/^[a-zA-Z0-9.?@\\/_-] $/';
var_dump(preg_match($str1, $regex));
// expected output: 1
var_dump(preg_match($str2, $regex));
// expected output: 0
  • Related