How to find if a variable contains certain character or not ? PHP

This question already has an answer here:

  • How do I check if a string contains a specific word? 37 answers

  • This will work:

    // use strpos() because strstr() uses more resources
    if(strpos("user input from search field", "-") === false)
    {
        // not found provides a boolean false so you NEED the ===
    }
    else
    {
        // found can mean "found at position 0", "found at position 19", etc...
    }
    

    strpos()

    What NOT to do

    if(!strpos("user input from search field", "-"))
    

    The example above will screw you over because strpos() can return a 0 (zero) which is a valid string position just as it is a valid array position.

    This is why it is absolutely mandatory to check for === false


    简单地使用这个strstr函数:

    $string= 'some string with - values ';
    if(strstr($string, '-')){
        echo 'symbol is isset';
    }
    
    链接地址: http://www.djcxy.com/p/13124.html

    上一篇: 检查单词是否在一组单词中

    下一篇: 如何找到一个变量是否包含某个字符? PHP