【问题标题】:PHP Like thing similar to MySQL Like, for if statement?PHP Like 类似于 MySQL Like 的东西,for if 语句?
【发布时间】:2011-06-22 04:31:47
【问题描述】:

我想要一个 if 语句,它使用与 mysql something LIKE '%something%' 相同的东西

我想在 php 中构建一个 if 语句。

if ($something is like %$somethingother%)

有可能吗?

我问这个问题的原因是我不想更改 MySQL 命令,这是一个很长的页面,上面有很多东西,我不想为此构建不同的函数。

让我知道这是否可能,如果可能,请告诉我该怎么做。

【问题讨论】:

    标签: php mysql if-statement


    【解决方案1】:

    like_match() 例子是最好的 这一个女巫 SQL 请求很简单(我以前使用过),但是当您通过数组键迭代时,like_match() 和 exost 数据库服务器资源的工作速度很慢,并且每一轮请求通常不需要请求的数据库服务器。我通过模式元素使其更快地切割/收缩数组,但数组上的正则表达式总是更快。 我喜欢 like_match() :)

    【讨论】:

      【解决方案2】:

      我认为值得一提的是 PHP 8 中的 str_contains() 函数,它执行区分大小写的检查,指示字符串是否包含在另一个字符串中,返回真或假。

      来自文档的示例:

      $string = 'The lazy fox jumped over the fence';
      
      if (str_contains($string, 'lazy')) {
          echo "The string 'lazy' was found in the string\n";
      }
      
      if (str_contains($string, 'Lazy')) {
          echo 'The string "Lazy" was found in the string';
      } else {
          echo '"Lazy" was not found because the case does not match';
      }
      
      //The above will output:
      //The string 'lazy' was found in the string
      //"Lazy" was not found because the case does not match
      
      

      查看完整文档here

      【讨论】:

        【解决方案3】:

        我最近遇到了这个要求并想出了这个:

        /**
         * Removes the diacritical marks from a string.
         *
         * Diacritical marks: {@link https://unicode-table.com/blocks/combining-diacritical-marks/}
         *
         * @param string $string The string from which to strip the diacritical marks.
         * @return string Stripped string.
         */
        function stripDiacriticalMarks(string $string): string
        {
            return preg_replace('/[\x{0300}-\x{036f}]/u', '', \Normalizer::normalize($string , \Normalizer::FORM_KD));
        }
        
        /**
         * Checks if the string $haystack is like $needle, $needle can contain '%' and '_'
         * characters which will behave as if used in a SQL LIKE condition. Character escaping
         * is supported with '\'.
         *
         * @param string $haystack The string to check if it is like $needle.
         * @param string $needle The string used to check if $haystack is like it.
         * @param bool $ai Whether to check likeness in an accent-insensitive manner.
         * @param bool $ci Whether to check likeness in a case-insensitive manner.
         * @return bool True if $haystack is like $needle, otherwise, false.
         */
        function like(string $haystack, string $needle, bool $ai = true, bool $ci = true): bool
        {
            if ($ai) {
                $haystack = stripDiacriticalMarks($haystack);
                $needle = stripDiacriticalMarks($needle);
            }
        
            $needle = preg_quote($needle, '/');
        
            $tokens = [];
        
            $needleLength = strlen($needle);
            for ($i = 0; $i < $needleLength;) {
                if ($needle[$i] === '\\') {
                    $i += 2;
                    if ($i < $needleLength) {
                        if ($needle[$i] === '\\') {
                            $tokens[] = '\\\\';
                            $i += 2;
                        } else {
                            $tokens[] = $needle[$i];
                            ++$i;
                        }
                    } else {
                        $tokens[] = '\\\\';
                    }
                } else {
                    switch ($needle[$i]) {
                        case '_':
                            $tokens[] = '.';
                            break;
                        case '%':
                            $tokens[] = '.*';
                            break;
                        default:
                            $tokens[] = $needle[$i];
                            break;
                    }
                    ++$i;
                }
            }
        
            return preg_match('/^' . implode($tokens) . '$/u' . ($ci ? 'i' : ''), $haystack) === 1;
        }
        
        /**
         * Escapes a string in a way that `UString::like` will match it as-is, thus '%' and '_'
         * would match a literal '%' and '_' respectively (and not behave as in a SQL LIKE
         * condition).
         *
         * @param string $str The string to escape.
         * @return string The escaped string.
         */
        function escapeLike(string $str): string
        {
            return strtr($str, ['\\' => '\\\\', '%' => '\%', '_' => '\_']);
        }
        

        上面的代码是 unicode 感知的,能够捕捉到这样的情况:

        like('Hello ?', 'Hello _'); // true
        like('Hello ?', '_e%o__');  // true
        like('asdfas \\?H\\\\%?É\\l\\_?\\l\\o asdfasf', '%' . escapeLike('\\?h\\\\%?e\\l\\_?\\l\\o') . '%'); // true
        

        您可以在 https://3v4l.org/O9LX0 上尝试所有这些

        【讨论】:

          【解决方案4】:

          如果您有权访问 MySQL 服务器,请使用 MySQLi 发送这样的查询:

          $SQL="select case when '$Value' like '$Pattern' then 'True' else 'False' end as Result";
          $Result=$MySQLi->query($SQL)->fetch_all(MYSQLI_ASSOC)[0]['Result'];
          

          结果将是一个包含 True 或 False 的字符串。让 PHP 做自己擅长的事,用 SQL 来点赞。

          【讨论】:

          • 我认为他或她只是在寻找类似的语法或 PHP 中的技巧来做与 sql 'like' 关键字相同的事情,但我不确定他/她是否使用数据库。
          • 也许有人无权访问 SQL 服务器,但这引出了问题。如果您不使用 SQL,为什么会考虑尝试在 PHP 中模仿 SQL 功能? PHP没有喜欢。它有正则表达式,如果你知道如何使用它会更好,但有问题。
          【解决方案5】:

          strpos() 不起作用,所以我必须使用这个 preg_match()

          $a = 'How are you?';
          
          if (preg_match('/\bare\b/', $a)) {
              echo 'true';
          }
          

          就像在这个例如我匹配单词“are” 希望对某人有所帮助

          【讨论】:

            【解决方案6】:

            使用这个函数,它的工作原理与 SQL LIKE 运算符相同,但它会返回布尔值,您可以使用另外一个 if 语句来创建自己的条件

            function like($str, $searchTerm) {
                $searchTerm = strtolower($searchTerm);
                $str = strtolower($str);
                $pos = strpos($str, $searchTerm);
                if ($pos === false)
                    return false;
                else
                    return true;
            }
            $found = like('Apple', 'app'); //returns true
            $notFound = like('Apple', 'lep'); //returns false
            
            if($found){
                // This will execute only when the text is like the desired string
            }
            

            【讨论】:

              【解决方案7】:

              但是您必须提供小写字符串才能正常工作。 strstr函数示例:

              $myString = "Hello, world!";
              echo strstr( $myString, "wor" );                    // Displays 'world!'
              echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ); // Displays 'No'
              

              【讨论】:

                【解决方案8】:

                我知道,这个问题并不实际,但我已经解决了类似的问题 :)

                我的解决方案:

                /**
                 * SQL Like operator in PHP.
                 * Returns TRUE if match else FALSE.
                 * @param string $pattern
                 * @param string $subject
                 * @return bool
                 */
                function like_match($pattern, $subject)
                {
                    $pattern = str_replace('%', '.*', preg_quote($pattern, '/'));
                    return (bool) preg_match("/^{$pattern}$/i", $subject);
                }
                

                例子:

                like_match('%uc%','Lucy'); //TRUE
                like_match('%cy', 'Lucy'); //TRUE
                like_match('lu%', 'Lucy'); //TRUE
                like_match('%lu', 'Lucy'); //FALSE
                like_match('cy%', 'Lucy'); //FALSE
                

                【讨论】:

                • 我喜欢它——一个小小的改变。图案线应为$pattern = str_replace('%', '.*', preg_quote($pattern,'/'));。否则 preg_match() 不会转义正斜杠。
                【解决方案9】:

                if ($something is like %$somethingother%)

                有可能吗?

                没有。

                我不想更改 MySQL 命令,这是一个很长的页面,上面有很多东西

                使用一些好的编辑器,它支持查找和替换中的正则表达式,并将其转换为:

                if(stripos($something, $somethingother) !== FALSE){
                
                }
                

                【讨论】:

                  【解决方案10】:

                  使用函数,在另一个字符串中搜索字符串,例如:strstrstrpossubstr_count

                  【讨论】:

                    【解决方案11】:

                    strstr函数

                    【讨论】:

                      猜你喜欢
                      • 2015-03-04
                      • 2013-02-28
                      • 2012-10-17
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2015-10-22
                      • 2016-09-13
                      • 1970-01-01
                      相关资源
                      最近更新 更多