-3

直奔主题

  echo str_replace('</h3><table','<?php echo 'Hello World!'; ?>',$doc->saveHTML());

在上面的代码中,php代码(<?php echo 'Hello World!'; ?>)是否会被执行?

4

2 回答 2

0

将 echo 语句放在结果也被回显的函数中是非常奇怪的。把你的代码,实际上它的结果放在一个变量中,让它在函数中被替换:

$replacement = 'Hell0 World';
echo str_replace('</h3><table', $replacement, $doc->saveHTML());

如果正确逃脱了路线,则替换变量可以包含您想要的所有内容。

于 2013-08-01T08:18:13.523 回答
0

No, your code won't be executed, but you want to escape the apostrophes. Every instance of ' should be replaced with \' in your code if you type it directly as string in PHP:

str_replace('</h3><table', '<?php echo \'Hello World!\'; ?>', $doc->saveHTML());

There is no need to escape anything if the code is already in a variable, is loaded from a file etc.

If you want to type your PHP code directly and you don't want to escape anything, you can use the HEREDOC syntax:

$str = <<<EOD
<?php echo 'Hello World!'; ?>
EOD;
echo str_replace('</h3><table', $str, $doc->saveHTML());

Now, everything in quotes ("" or '') is a string and will not be executed. So if you want the code to be executed, don't put it into quotes. This cannot be easily explained with echo, but you already told it's just a sample, so let's assume you want to use the rand() function instead.

In this case, you don't want to do this:

str_replace('</h3><table', '<?php echo rand(); ?>', $doc->saveHTML());

but all you need is:

str_replace('</h3><table', rand(), $doc->saveHTML());

The last problem is you should execute the code before you call the str_replace function. This will be useful if you have a lot of code you want to execute:

$replacement = rand();
str_replace('</h3><table', $replacement, $doc->saveHTML());
于 2013-08-01T08:04:12.750 回答