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

r1zhe5dt  于 2023-11-20  发布在  PHP
关注(0)|答案(1)|浏览(144)

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

$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


有没有办法用一个简单的脚本来实现这一点?

gkn4icbw

gkn4icbw1#

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

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

字符串

相关问题