tags:

views:

50

answers:

3

Hi all

i want to create a regular expression which will allow only spaces and number..

And how can i check this with PHP?

Thanks in advance Avinash

+2  A: 

This should work:

^[\s\d]*$

You should probably specify if you want "zero or more" or "one or more" spaces. The above allows for an empty string to pass evaluation.

Rich
This one is exactly like the one I posted, except allows empty strings to pass, and tabs instead of spaces, if they happen.
DevelopingChris
\s allows all kind of characters, assuming he wants to allow only 'space' (0x32) it's not enough.
Boris Guéry
+3  A: 

The regex is as follows.

/^[\d ]+$/i

To answer how you run it in php, I need to know the context, do you need it to run on a single line or multi line input? do you need it to run in a loop?

DevelopingChris
single line only about 15 chars only
Avinash
+3  A: 
$pattern = '/^[0-9 ]+$/';

if ( preg_match ($pattern, $text) )
{
    echo 'allowed';
}

Edit:

If you want to limit to 15 chars (as you mentioned in a comment) you can use { } to delimit a min and a max lenght.

pattern becomes :

$pattern = '/^[0-9 ]{1,15}$/';

to allow 1 to 15 chars.

Boris Guéry