本文介绍了如何在此正则表达式中允许空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式非常业余,我如何在这个正则表达式中允许空格(不管有多少)?

I'm such an amateur at regex, how do I allow spaces(doesn't matter how many) in this regex?

if(preg_match('/[^A-Za-z0-9_-]/', $str)) return FALSE;

推荐答案

if(preg_match('/[^A-Za-z0-9_ -]/', $str)) return FALSE;

请注意,我将空格放在连字符之前.如果空格在连字符之后,我将指定从下划线到空格的字符范围.(问题也可以通过在连字符前加一个反斜杠来逃避.)

Note that I put the space before the hyphen. If the space were after the hyphen, I would be specifying a character range from underscore to space. (Issue also evadable by putting a backslash before the hyphen to escape it.)

这假设您所说的允许"是指:此正则表达式用于验证字符串,如果它匹配,则该字符串被禁止em>(因此 return FALSE).所以否定字符类([^...])中的字符实际上是允许的字符.(这在这个问题中引起了一些普遍的混淆.)

This is assuming that what you mean by "allow" is: this regex is being used to validate a character string, and if it matches, then the character string is disallowed (hence return FALSE). So the characters in the negated character class ([^...]) are actually the allowed characters. (This is causing some general confusion in this question.)

这篇关于如何在此正则表达式中允许空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:29