Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for matching number and spaces

Tags:

regex

php

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

And how can i check this with PHP?

like image 653
Avinash Avatar asked Apr 23 '10 13:04

Avinash


People also ask

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do I match a number in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

Can you have spaces in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.


2 Answers

$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.

like image 116
Boris Guéry Avatar answered Sep 22 '22 16:09

Boris Guéry


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?

like image 22
DevelopingChris Avatar answered Sep 25 '22 16:09

DevelopingChris