Using a string as an expression to be send to eval() and replacing a sub-string with a vriable value PHP

不羁的心 提交于 2019-12-12 00:30:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!