等于SQL的%,如%,但在PHP中

时间:2014-02-08 18:08:16

标签: php sql equals

PHP中的任何函数是否等于SQL的%,如%?

E.g。

$a = 'I drove the Car';
$b = 'i_drove_the_car';

if(like($a, $b))
{
 echo "The strings have an %like% match";
}

3 个答案:

答案 0 :(得分:3)

使用strstr,或者,如果您不区分大小写,请stristr

if(strstr($a, $b)) {
    echo "$b is in $a";
}

答案 1 :(得分:2)

您可以使用正则表达式,即preg_match

if (preg_match('#.*' . $b . '.*#/i', $a)) {
    echo 'smth';
}

选项i表示案例说明性数学。

答案 2 :(得分:0)

除了上述解决方案之外,如果您尝试使用“%absc%ehf%”等多个部分,则以下脚本将有所帮助。您需要将不同的部分作为数组中的不同元素。这里,数组是数组('absc','ehf')

// mainStr is the string you are searching and $partsArray holds the like parts 
// in array like explained above 
function like($mainStr, $partsArray) {
  if (empty($partsArray)) {
      return true;
  }

  $lastIndex = 0;
  // checks to see that strings exist after each other. In the example above, 
  // "%absc%ehf%" would first check the existence of absc and then if it exists 
  // it would continue checking the rest of the string for the rest of like parts 
  foreach($partsArray as $part) {
     $pos = strpos($mainStr, $part);
    if ( $pos === false || $pos < $lastIndex) {
        return false;
    } 
    $lastIndex += $pos + strlen($part); 
  }
  return true;

}
相关问题