检查字符串是否包含PHP中的下划线

2 php regex

我想知道一个轻量级的方法来查找字符串是否包含下划线(_).作为奖励,如果有可能有一个if语句,不仅检查下划线检查字符串是否只连接两个字.

例如,我正在寻找像"foo_bar"这样的字符串.

没有空格,只有两个单词和一个下划线.

任何帮助都会很棒,

谢谢!

Kar*_*lis 7

例: preg_match('/^[^\W_]+_[^\W_]+$/', $string);

  • @Shef不.你的正则表达式也匹配`aaa_bbb_ccc` :) (3认同)
  • `^ [\ w] + _ [\ w] + $`匹配`___`但是,`^ [^\W _] + _ [^\W _] +`没有. (2认同)

She*_*hef 5

$str = 'foo_bar';
if (preg_match('/^[a-z]+_[a-z]+$/i', $str)) {
    // contains an underscore and is two words
} else {
    // does not contain two words, or an underscore
}
Run Code Online (Sandbox Code Playgroud)

  • `preg_match('/.+_.+/','foo__')== 1` (2认同)