用于比较两个变量的PHP函数?

时间:2014-10-17 18:27:18

标签: php

是否存在用于比较两个字符串变量和第三个参数的PHP函数是比较运算符并返回布尔值。

示例:

$string1 = "Foo";
$string2 = "Bar";
$result = php_function_for_comparing($string1, $string2, "=="); //return boolean

提前致谢。

4 个答案:

答案 0 :(得分:1)

您可以使用eval。

function compare($a, $b, $op) {
  return eval('return $a ' . $op . ' $b;');
}

答案 1 :(得分:0)

好吧,你可以使用eval函数 - 但请注意,eval执行传递给它的任何php代码。所以你必须正确验证给该方法的任何输入!

http://php.net/manual/en/function.eval.php

$operator1 = "==";
$operator2 = "!=";

$string1 = "'foo'"; //quote them for evaluation, or you receive syntax errors
$string2 = "'bar'"; //quote them for evaluation, or you receive syntax errors

if (eval("return ".$string1 . $operator1 . $string2.";")){
   echo "Equal!";
}

if (eval("return ".$string1 . $operator2 . $string2.";")){
   echo "Different!";
}

或不引用先前的值:

$operator1 = "==";
$operator2 = "!=";

$string1 = "foo"; 
$string2 = "bar";

//this passes the strings $string1 and $string2 - which will THEN 
//be evaluated to the values.
if (eval('return $string1' . $operator1 . '$string2;')){ 
   echo "Equal!";
}

if (eval('return $string1' . $operator2 . '$string2;')){
   echo "Different!";
}

答案 2 :(得分:0)

要回答我的问题,我创建了一个简单的函数,而不使用php eval()。

function variable_comparison($condition = "==", $var1, $var2 = false){
    if($condition == "is_empty")
        return empty($var1);
    else if($condition == "is_filled")
        return !empty($var1);
    else if($condition == "==")
        return $var1 == $var2;
    else if($condition == "!=")
        return $var1 != $var2;
    else if($condition == ">")
        return $var1 > $var2;
    else if($condition == "<")
        return $var1 < $var2;
    else if($condition == ">=")
        return $var1 >= $var2;
    else if($condition == "<=")
        return $var1 <= $var2;
    else if($condition == "in_array")
        return in_array($var1, $var2);
    else if($condition == "contains")
        return strpos($var1, $var2);
    else if($condition == "starts_with")
        return substr($var1, 0, strlen($var2)) === $var2;
    else if($condition == "ends_width"){
        $length = strlen($var2);
        return !$length || substr($var1, - $length) === $var2;
    }       
}

当您编写基本条件逻辑并将其保存为sting时,此函数非常有用。

示例条件逻辑字符串:

$string_logic = "{if post_[foo]<!=>post_[bar]?post_[bar]:Defalut Value Here!}";

结果如下:

echo ($_POST["foo"] != $_POST["bar"]) ? $_POST["bar"] : "Default Value Here!";

但是当然你需要创建一个递归算法来评估字符串并将其转换为PHP可读代码。

答案 3 :(得分:-1)

是的很多,你可以聪明地将它们用作布尔

//Calculate the percentage of similarities
similar_text ($first , $second, $percent )

levenshtein($str1, $str2) //Calculate Levenshtein distance between two strings

soundex($str) //Calculate the soundex key of a string