问题
I need some help with basic syntax in PHP,
I got the following string :$str = "return (strlen(replace) <= 5 && strlen(replace) >= 1);";
and I got a variable : $var = "VariableValue";
and the st_replace function as : str_replace('replace', $var, $str);
What I am trying to do is actually use eval in somehing like:
if(eval($str)){//This should now make the if condition **look like**
//if(strlen(*'VariableValue'*)...)
//
echo 'Success';
}else{
echo 'Ask the guys at StackOverFlow :),sure after searching for it';
}
So if you notice what is if(strlen('VariableValue')...) this is what I want to do,make the final if statement after eval containing the vars value WITH QUOTES so strlen actually process it,
I hope I made clear as needed :)
Thanks in advance
回答1:
Try it like this
$str = "return (strlen(##replace##) <= 5 && strlen(##replace##) >= 1);";
$var = 'test';
// you have to assign the str_replace to $str again. And use " around the $var.
$str = str_replace('##replace##', '"' . addslashes($var) . '"', $str);
if (eval($str)) {
echo 'Success';
}
else {
echo 'Ask the guys at StackOverFlow :),sure after searching for it';
}
I added the ## around replace because it's a good idea to always have a somewhat unique string to replace... like when you expand your eval'd code to include str_replace
, then that would be replaced too otherwise.
EDIT
Escaped the $var with addslashes
as per @Erbureth's comment.
回答2:
aYou don't need eval() for that (there are reason why it is sometimes called evil()...).
Just try a condition like that:
if ( (strlen($var) <= 5) && (strlen($var) >= 1) )
来源:https://stackoverflow.com/questions/12744654/using-a-string-as-an-expression-to-be-send-to-eval-and-replacing-a-sub-string