展开反向正则表达式以允许 1 个空格字符
如何更改下面的模式以允许 1 个空格字符?
$name = 'too long name';
$pattern_name = '/[^a-zA-Z]/';
if (preg_match($pattern_name,$name)) { // remove any non-letter characters
$name = preg_replace($pattern_name,'',$name);
$errors['name'] = 'Invalid characters found and removed in name';
}
使用这些模式中的任何一个都不起作用:
$pattern_name = '/[^a-zA-Z ?]/';
$pattern_name = '/[^a-zA-Z] ?/';
预期结果是匹配,因为 $name 中存在 2 个空格字符,因此 if 语句应该为 true,并且替换函数将更新 $name,因此其值将变为“too longname”。
How can I alter the pattern below to allow 1 space character ?
$name = 'too long name';
$pattern_name = '/[^a-zA-Z]/';
if (preg_match($pattern_name,$name)) { // remove any non-letter characters
$name = preg_replace($pattern_name,'',$name);
$errors['name'] = 'Invalid characters found and removed in name';
}
Using either of these patterns does not work:
$pattern_name = '/[^a-zA-Z ?]/';
$pattern_name = '/[^a-zA-Z] ?/';
Expected result is a match, since 2 space characters exists in $name, thus the if-statement should be true and the replace function will update $name so its value will become "too longname".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须使您的模式更加明确。如果最多可以有一个空格,并且它必须被字母包围,那么:
You'll have to make your pattern more explicit. If you can have one space at maximum, and it must be surrounded by letters, then:
它应该像在括号中添加空格一样简单。
It should be as simple as adding a space in the brackets.
我会反转正则表达式,而不是尝试查找无效字符,而是匹配有效名称(这是您正在做的事情吗?)。这给了我们这个正则表达式:
/[a-zA-Z]+ [a-zA-Z]+/
。匹配有效字符、一个空格,然后匹配更多有效字符。I'd invert the regex, and instead of trying to find invalid characters, match valid names (is that what you are doing?). That gives us this regex:
/[a-zA-Z]+ [a-zA-Z]+/
. Match valid characters, one space and then more valid characters.