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

别说谁变了你拦得住时间么 提交于 2019-12-03 05:36:01

问题


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.


回答1:


Use

preg_match('/^[a-z0-9 .\-]+$/i', $firstname)



回答2:


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}




回答3:


The only difficult bit here is the dash.

For spaces and dots, you can simply add them to your character class, like so:

'/^[a-zA-Z0-9 .]+$/'

Easy.

The dash is slightly harder because hyphens have special meaning in a character class like this (as you already know, they're used for ranges of characters like a-z). In order to specify a hyphen in a character class, it must be the first character in the class (ie it must not be between two characters, otherwise it is treated as a character range marker).

So your expression would be:

'/^[-a-zA-Z0-9 .]+$/'

Hope that helps.



来源:https://stackoverflow.com/questions/17085738/php-only-allow-letters-numbers-spaces-and-specific-symbols-using-pregmatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!