i want to create a regular expression which will allow only spaces and number..
And how can i check this with PHP?
\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.
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.
[] 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 .
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.
$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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With