代码之家  ›  专栏  ›  技术社区  ›  ondrobaco

如果字符串至少包含一个问号,则regex返回false

  •  0
  • ondrobaco  · 技术社区  · 15 年前

    我有一个字符串,我想检测它是否包含至少一个问号。如果它确实返回false。我试着去寻找它,但是questiomark似乎是一个特殊的角色。你会怎么做?

    谢谢您。

    2 回复  |  直到 15 年前
        1
  •  5
  •   Paul Kehrer    15 年前

    你只需要逃避?在你的正则表达式中。 preg_match('/\?/','A string?',$matches) 将返回匹配项?如果有的话。

    也就是说,你可以用 strpos() 为了这个。它会更快,因为你不需要一个正则表达式引擎来找到?

        2
  •  3
  •   Community Mohan Dere    9 年前

    不需要正则表达式。

    if (strpos($str, '?') !== false) { 
        return false;
    }
    
    // Shorter but always executes due to lack of a conditional structure
    // May not be what you need if you're doing various other checks
    return strpos($str, '?') === false;
    

    但你是对的, ? 是正则表达式中的一个特殊字符。它告诉regex引擎查找零次或一次出现的内容。

    Paul Kehrer says 你可以简单地用反斜杠来逃避它。

    推荐文章