php preg_match 仅允许字母、空格和破折号和空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13830745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:08:19  来源:igfitidea点击:

preg_match only letters, spaces and dashes and spaces allowed

php

提问by Alexand657

i know that one condition that im currently using where it gives an error if $stringabc contains anything but numbers is :

我知道我当前使用的一个条件是,如果 $stringabc 包含除数字以外的任何内容,则会出现错误:

if(preg_match("/[^0-9]/",$stringabc))

I want an if condition where it gives an error if $stringdef contains anything but letters, spaces and dashes (-).

我想要一个 if 条件,如果 $stringdef 包含除字母、空格和破折号 (-) 以外的任何内容,它会给出错误。

回答by mvds

That would be:

那将是:

if(preg_match('/[^a-z\s-]/i',$stringabc))

for "anything but letters (a-z), spaces (\s, meaning any kind of whitespace), and dashes (-)".

对于“除字母 (az)、空格(\s,表示任何类型的空格)和破折号 (-) 之外的任何内容”。

To also allow numbers:

还允许数字:

if(preg_match('/[^0-9a-z\s-]/i',$stringabc))

回答by jeroen

You can use something like:

您可以使用以下内容:

preg_match("/[^a-z0-9 -]/i", $stringabc)

回答by DrinkJavaCodeJava

If you want to stop all whitespace, another way you could do it is

如果您想停止所有空格,另一种方法是

preg_match("/^[a-z[[:space:]]-]/i",$stringabc);