Search code examples
phpregexstringvalidationpreg-match

PHP preg_match to allow only numbers,spaces '+' and '-'


I need to check to see if a variable contains anything OTHER than 0-9 and the "-" and the "+" character and the " "(space).

The preg_match I have written does not work. Any help would be appreciated.

<?php

$var="+91 9766554433";

if(preg_match('/[0-9 +\-]/i', $var))
 echo $var;
?>

Solution

  • You have to add a * as a quantifier to the whole character class and add anchors to the start and end of the regex: ^ and $ means to match only lines containing nothing but the inner regex from from start to end of line. Also, the i modifier is unnecessary since there is no need for case-insensitivity in this regex.

    This should do the work.

    if(!preg_match('/^[0-9 +-]*$/', $var)){
         //variable contains char not allowed 
    }else{
         //variable only contains allowed chars
    }