preg_match php 中包含 -(连字符)的特定模式

preg_match specific pattern containing - (hyphen) in php

我想要 preg_match 一个看起来像这样的字符串(如下),我尝试了其他方法,但它们对特定字符串都有效

firstname

first-name

除此之外,拒绝另一个字符串

我尝试这样做,但做不到,我想通了,这只有使用正则表达式才有可能,而且由于我对正则表达式一无所知,所以我不能在一分钟左右完成并且运行 一个易受攻击的代码,如果不是 regex

,我们还有其他方法吗

转到https://www.regex101.com/

尝试 (first[\-]{0,1}name)

工作正常:-)

php代码:

$pattern = '(first[\-]{0,1}name)';
echo preg_match($pattern,'firstname');

echo preg_match($pattern,'first-name');

输出:11 - 这意味着 true - true

您可以用 ? 符号匹配 0 或 1 个连字符:

if( preg_match('/^first-?name$/', $yourString ) ){
    // matched.
}

^$ 符号是开始和结束标记,添加是为了确保字符串准确无误。

怎么样:

preg_match('/^\w+-?\w+$/', $string);