Check if string contains an underscore in PHP

限于喜欢 提交于 2021-02-10 12:29:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!