PHP:正则表达式匹配字符串前面没有数字或空格
我一直在尝试检查字符串值是否以数值或空格开头并采取相应的操作,但它似乎不起作用。这是我的代码:
private static function ParseGamertag( $gamertag )
{
$safetag = preg_replace( "/[^a-zA-Z0-9\s]+/", "", $gamertag ); // Remove all illegal characters : works
$safetag = preg_replace( "/[\s]+/", "\s", $safetag ); // Replace all 1 or more space characters with only 1 space : works
$safetag = preg_replace( "/\s/", "%20", $safetag ); // Encode the space characters : works
if ( preg_match( "/[^\d\s][a-zA-Z0-9\s]*/", $safetag ) ) // Match a string that does not start with numerical value : not working
return ( $safetag );
else
return ( null );
}
所以 hiphop112
有效,但 112hiphip
无效。 0down
无效。
第一个字符必须是字母字符[a-zA-Z]
。
I've been trying to check if a string value starts with a numerical value or space and act accordingly, but it doesn't seem to be working. Here is my code:
private static function ParseGamertag( $gamertag )
{
$safetag = preg_replace( "/[^a-zA-Z0-9\s]+/", "", $gamertag ); // Remove all illegal characters : works
$safetag = preg_replace( "/[\s]+/", "\s", $safetag ); // Replace all 1 or more space characters with only 1 space : works
$safetag = preg_replace( "/\s/", "%20", $safetag ); // Encode the space characters : works
if ( preg_match( "/[^\d\s][a-zA-Z0-9\s]*/", $safetag ) ) // Match a string that does not start with numerical value : not working
return ( $safetag );
else
return ( null );
}
So hiphop112
is valid but 112hiphip
is not valid. 0down
is not valid.
The first character must be an alphabetical character [a-zA-Z]
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要使用锚点
^
将模式锚定到字符串的开头,否则您的正则表达式将在字符串中的某个位置找到有效的匹配项
您可以找到锚点的解释 这里位于regular-expressions.info
请注意
^
的不同含义。在字符类外部,它是字符串开头的锚点,在字符类内部,第一个位置是该类的否定。You need to anchor your pattern to the start of the string using an anchor
^
Otherwise your regex will find a valid match somewhere within the string
You can find a explanation of anchors here on regular-expressions.info
Note the different meaning of the
^
. Outside a character class its an anchor for the start of the string and inside a character class at the first position its the negation of the class.尝试添加
^
来表示字符串的开头...另外,如果第一个字符必须是字母,这可能会更好:
Try adding the
^
to signify the beginning of the string...also, if the first character has to be a letter, this might be better:
使用
^
标记字符串的开头(尽管[ ]
内的^
表示不是)。您还可以使用
\w
代替a-zA-Z0-9
Use
^
to mark the beginning of the string (although^
inside[ ]
means not).You can also use
\w
in place ofa-zA-Z0-9
在正则表达式的开头添加“以胡萝卜开头”:
Add the "begins with carrot" at the beginning of the regex:
首先,没有任何内容可以匹配 \s,因为您已将所有空格替换为 %20。
为什么不直接正向匹配:
First thing, nothing will match \s as you have replaced all spaces by %20.
Why not just match positively: