问题
I'm was wondering of a lightweight way of finding if a string contains an underscore (_). As a bonus if it was possible to have an if statement that not only checks for an underscore checks if the string is only two words connected.
E.g I'm looking to check for strings like this "foo_bar".
With no spaces, just the two words and an underscore.
Any help would be great,
Thanks!
回答1:
$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:
Example: preg_match('/^[^\W_]+_[^\W_]+$/', $string);
回答3:
$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
回答4:
For example:
preg_match('#^[a-zA-Z1-9]+_[a-zA-Z1-9]+$#','foo_bar');
See here for some really good tutorial on what all that means.
回答5:
Here you go: http://www.php.net/manual/en/function.substr-count.php
You could also do something like:
count( array_filter( explode( '_', str_replace( " ", "_", "foo_bar" ) ) ) ) // == 2
回答6:
if(str_replace("_", "", $x) != $x) {
// There is an underscore
}
来源:https://stackoverflow.com/questions/6821679/check-if-string-contains-an-underscore-in-php