Coderhhz
Coderhhz

Reputation: 340

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

Upvotes: 4

Views: 12483

Answers (4)

Martin
Martin

Reputation: 2414

Try see if this works. I haven't gotten around to test it beforehand, so I apologize if it doesn't work.

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

Upvotes: 0

cb0
cb0

Reputation: 8613

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
}

Upvotes: 7

Toto
Toto

Reputation: 91385

Just negate the character class:

if ( preg_match('/[^0-9 +-]/', $var) )
    echo $var;

or add anchors and quantifier:

if ( preg_match('/^[0-9 +-]+$/', $var) )
    echo $var;

The case insensitive modifier is not mandatory in your case.

Upvotes: 2

shibli049
shibli049

Reputation: 538

You can try regex101.com to test your regex to match your criteria and then on the left panel, you'll find code generator, which will generate code for PHP, Python, and Javascript.

$re = "/^[\\d\\s\\+\\-]+$/i"; 
$str = "+91 9766554433"; 

preg_match($re, $str, $matches);

You can take a look here.

Upvotes: 0

Related Questions