Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php only allow letters, numbers, spaces and specific symbols using pregmatch

on my php i use preg_match to validate input texts.

if(preg_match('/^[a-zA-Z0-9]+$/', $firstname)) { } 

But this only allows alphanumeric and does not allow spaces. I want to allow spaces, alpha and numeric. and period(.) and dash(-)

Please help me out here? thanks in advance.

like image 400
CudoX Avatar asked Jun 13 '13 11:06

CudoX


People also ask

What is the use of Preg_match () method?

The preg_match() function returns whether a match was found in a string.

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

How do you check if a string contains only alphabets and spaces in PHP?

A ctype_alpha() function in PHP used to check all characters of a given string are alphabetic or not. If all characters are alphabetic then return True otherwise return False.

What does preg match return?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


2 Answers

Use

preg_match('/^[a-z0-9 .\-]+$/i', $firstname) 
like image 65
Baba Avatar answered Sep 24 '22 23:09

Baba


If you not only want to allow ASCII, then use Unicode properties:

preg_match('/^[\p{L}\p{N} .-]+$/', $firstname) 

\p{L} is any letter in any language, matches also Chinese, Hebrew, Arabic, ... characters.

\p{N} any kind of numeric character (means also e.g. roman numerals)

if you want to limit to digits, then use \p{Nd}

like image 24
stema Avatar answered Sep 23 '22 23:09

stema