识别并执行字符串上的php代码 [英] identify and execute php code on a string

查看:57
本文介绍了识别并执行字符串上的php代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在字符串中执行php代码.我的意思是,如果我有

I would like to know if it's possible to execute the php code in a string. I mean if I have:

$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";

有人知道吗?

似乎没人能理解.我想保存一个像这样的字符串

It looks like nobody understood. I wanna save a string like

$string = If i say <?php count(array('lala'));?>

在数据库中,然后呈现它.我可以使用

in a database and then render it. I can do it using

function render_php($string){
    ob_start();
    eval('?>' . $string);
    $string = ob_get_contents();
    ob_end_clean();
    return $string;
}

问题是我没有将php代码重新整理成

The problem is that I does not reconize php code into "" (quotes) like

I say "<?php echo 'dada'; ?>"

推荐答案

$string = ($test === TRUE) ? 'lala' : 'falala';

有很多方法可以完成您要尝试执行的操作(如果我正在阅读正确编写的内容).以上是三元.如果条件的计算结果为true,则$ string将设置为"lala",否则将设置为"falala".

There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.

如果您确实是在问您写了什么,请使用eval()函数.它接受一个传递的字符串并像执行PHP代码一样执行它.不要包含<?php ?>标签.

If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.

function dropAllTables() {
    // drop all tables in db
}

$string = 'dropAllTables();';

eval($string); // will execute the dropAllTables() function

您可以使用以下正则表达式查找所有php代码:

You can use the following regular expression to find all the php code:

preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);

$ php_code将是一个数组,其中$ php_code [0]将返回带有代码+ <?php ?>标记的所有匹配项的数组. $ php_code [2]将是一个仅包含要执行的代码的数组.

$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.

所以

$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));

这应该对您想做的事情有帮助.

This should be helpful for what you want to do.

这篇关于识别并执行字符串上的php代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆