我想知道一个轻量级的方法来查找字符串是否包含下划线(_)。 作为奖励,如果有可能有一个if语句,不仅检查下划线检查字符串是否只连接两个单词。
E.g 我正在寻找像这样的字符串“foo_bar”。
没有空格,只有两个单词和下划线。
任何帮助都会很棒,
谢谢!
答案 0 :(得分:7)
示例:preg_match('/^[^\W_]+_[^\W_]+$/', $string);
答案 1 :(得分: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
}
答案 2 :(得分:4)
$mystring = "hello_there";
$pos = strpos($mystring, '_');
if(false !== $pos) {
//no _ in the mystring
}
else {
echo "_ found at pos ".$pos;
}
//in this example else part will execute
答案 3 :(得分:2)
例如:
preg_match('#^[a-zA-Z1-9]+_[a-zA-Z1-9]+$#','foo_bar');
请参阅here for some really good tutorial on what all that means.
答案 4 :(得分:1)
在这里:http://www.php.net/manual/en/function.substr-count.php
您还可以执行以下操作:
count( array_filter( explode( '_', str_replace( " ", "_", "foo_bar" ) ) ) ) // == 2
答案 5 :(得分:-1)
你甚至可以做一个简单的$x = explode('_', $string)
,然后看看是否有count($x)
的结果
答案 6 :(得分:-1)
if(str_replace("_", "", $x) != $x) {
// There is an underscore
}