问题描述:

THIS IS CODE:

<?php

$str = "AEIOU 086432";

$con = "(1 == 1) && " ;

$con = $con.'(preg_match("/U/", $str)) && ';

$con = $con.'(preg_match("/82/", $str)) && ';

$con = "(2 == 2)" ;

if($con){

echo "Found" ;

}

else{

echo "Not Found" ;

}

?>

This answer should "Not found". Where is the problem?

网友答案:

This is your solution:

<?php
function p($str){
$con = (1 == 1)  ;
$con = $con &&  (preg_match("/U/", $str));  
$con = $con &&  (preg_match("/0865/", $str)) ; 
$con =  $con &&  (2 == 2);
return $con;
}

$str = "AEIOU 086432";
//var_dump( filter_var($con, FILTER_VALIDATE_BOOLEAN));

if(  p($str) ){
echo "Found" ;
}

else{
echo "Not Found" ;
}
?>

Hopefully you will be satisfied.....

网友答案:

(bool)'2 == 2' is false. Should it be true?

You have there mistake, on the 6th line dot is missing to concatenate strings.

$con .= "(2 == 2)" ;   
//   ^

You need to use eval to get Found, but better is to avoid using similar solutions and make it normally.

$str = "AEIOU 086432";
if ((1 == 1) && (preg_match("/U/", $str)) &&  (preg_match("/82/", $str)) &&  2 == 2)) {
    echo 'Found';
}  else {
    echo 'Not found';
}

Conditions 1 == 1 and 2 == 2 could be removed, they are always true.

网友答案:

Paraphrasing the comments:

I want to invent a mock-SQL language for filtering data stored in an array.

You don't need to invent "PHPQL". SQL is a text based query language because it provides a universally usable text based interface to a data storage system. You do not need to invent such a universal text language; just write PHP code. If you can write things like $con = $con.'(preg_match("/U/", $str)) && ', you can also write actual code:

$results = array_filter($data, function (array $item) {
    return preg_match('/U/', $item['key']) && ..
});

This filters your data array by whatever conditions you want, with the conditions being supplied as a callback function.

网友答案:

You are using the variable $con as a boolean while it contains a string value:

if ($con) {
    echo "Found";
} else {
    echo "Not Found";
}

Take a look at the documentation page about type juggling and the way strings are converted to booleans.

At that point, the value of variable $con is (2 == 2) and that evaluates to TRUE when converted to boolean.

Take also a look at the strings documentation, the section named Useful functions and operators clearly states:

Strings may be concatenated using the '.' (dot) operator.

相关阅读:
Top