【问题标题】:Test if a string contains a word in PHP?测试一个字符串是否包含 PHP 中的一个单词?
【发布时间】:2012-02-25 12:10:23
【问题描述】:

在 SQL 中,我们有 NOT LIKE %string%

我需要在 PHP 中执行此操作。

if ($string NOT LIKE %word%) { do something }

我认为strpos()可以做到这一点

但不知道怎么...

我确实需要有效 PHP 中的比较句。

if ($string NOT LIKE %word%) { do something }

【问题讨论】:

  • 我更新了标题以更好地反映问题。单词匹配的确切语义也应该被列出。在某些情况下使用\bword\b\bword|word\b 可能会更好。

标签: php string-comparison


【解决方案1】:
if (strpos($string, $word) === FALSE) {
   ... not found ...
}

注意strpos() 区分大小写,如果您想要不区分大小写的搜索,请改用stripos()

还要注意===,强制进行严格的相等测试。如果“needle”字符串位于“haystack”的开头,strpos 可以返回有效的0。通过强制检查实际的布尔值 false(也称为 0),您可以消除误报。

【讨论】:

  • 请注意,%word% 是通配符,而不是变量... $string 包含 char 形式的 IP 地址,如 $string = 123.456.789.100,我想排除(不喜欢) 以 123.456% 开头的那些
  • @LucasMatos Then $word = "word" then ... 虽然它是一个通配符,但 strpos 涵盖了一个非常微不足道的用法(“浮动末端”)(实际上它是 因为 strpos 在这里工作!)。 $word = "a?b" 不适用于这种方法,如果 ? 旨在“匹配任何字符”,例如
  • @LUcas:那么应该在问题中这么说。简单的例子得到简单的答案。
  • 这就是我的句子看起来像if ($viewer_ip AND $viewer_ip != $last_viewer_ip AND strpos($viewer_ip, 66.249) === false) { 我想从我的计数器中排除谷歌的机器人 ips。只需等待其中一个到达我的站点即可检查其是否正常工作。谢谢大家
  • 对这样的“裸”浮点数要非常小心。 PHP 可能会使用与您预期不同的尾随小数对其进行字符串化。强制它是一个带有66.249 的字符串,而不是它会找到像166.249 这样的东西。如果那是字符串的开头,您可以将 === 更改为简单的 >,以排除开头的任何匹配项。
【解决方案2】:

使用strpos。如果未找到该字符串,则返回false,否则返回不是false。请务必使用类型安全的比较 (===),因为可能会返回 0,它是一个虚假值:

if (strpos($string, $substring) === false) {
    // substring is not found in string
}

if (strpos($string, $substring2) !== false) {
    // substring2 is found in string
}

【讨论】:

    【解决方案3】:
    <?php
    //  Use this function and Pass Mixed string and what you want to search in mixed string.
    //  For Example :
        $mixedStr = "hello world. This is john duvey";
        $searchStr= "john";
    
        if(strpos($mixedStr,$searchStr)) {
          echo "Your string here";
        }else {
          echo "String not here";
        }
    

    【讨论】:

    • 如果 $searchStr 在 $mixedStr 的开头,这将失败。在该示例中,如果您搜索“hello”,您将回显“String not here”,因为 strpos 将返回 0,这将分支到 else 条件。检查 strpos 的返回值时始终使用 ===。
    【解决方案4】:

    use 
    
    if(stripos($str,'job')){
       // do your work
    }

    【讨论】:

    • job$str 的前三个字符时,这将失败。更正此无法解释的 sn-p 将使其成为此页面上的重复答案。此帖子可以安全删除。
    猜你喜欢
    • 2015-09-16
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多