使用 PHP preg_match 检查多个和组合模式

问题描述 投票:0回答:2

我不想在字符串中允许多种模式,例如,

$string = "php in  stackoverflow"; // multiple spaces not allowed
$string = "php in--stackoverflow"; // multiple hyphens not allowed
$string = "php in__stackoverflow"; // multiple underscores not allowed
etc

所以,它适用于这些行,

if(preg_match('/\s\s+/', $string)) echo "only a single spaces are allowed";
if(preg_match('/\-\-+/', $string)) echo "only a single hyphens are allowed";
if(preg_match('/\_\_+/', $string)) echo "only a single underscores are allowed";

我也不想让下面的组合模式和上面的行不起作用,

$string = "php in -stackoverflow"; // a space with a hyphen not allowed
$string = "php in-_stackoverflow"; // a hyphens with a underscore not allowed
$string = "php in_ stackoverflow"; // a underscore with a space not allowed
etc

知道我可以用一个简单的脚本来实现这一点吗?

php regex preg-match
2个回答
2
投票

这就是字符类的用途,匹配多个字符。

if(preg_match('/[\s-_][\s-_]+/', $string)) echo "only a single space, hyphen or underscore is allowed";

0
投票

preg_match('/--+|^-+|-+$/', $string)

这在 else if 中失败。但单独来看它是有效的。有什么想法吗??

© www.soinside.com 2019 - 2024. All rights reserved.