在随机文本的echo中包含php代码

在随机文本的echo中包含php代码,php,random,echo,Php,Random,Echo,我想随机显示一个php代码,所以对于我来说 <?php // load the file that contain thecode $adfile = "code.txt"; $ads = array(); // one line per code $fh = fopen($adfile, "r"); while(!feof($fh)) { $line = fgets($fh, 10240); $line = trim($line); if($line != "") {

我想随机显示一个php代码,所以对于我来说

<?php

// load the file that contain thecode
$adfile = "code.txt";
$ads = array();

// one line per code
$fh = fopen($adfile, "r");
while(!feof($fh)) {

  $line = fgets($fh, 10240);
  $line = trim($line);
  if($line != "") {
    $ads[] = $line;
  }
}

// randomly pick an code
$num = count($ads);
$idx = rand(0, $num-1);

echo $ads[$idx];
?>
如何使echo显示php代码,而不是php代码的txt版本?

使用eval:

编辑:

或者更好的是,使用包括。这可以是if-else语句、switch语句、数组或任何可以从选项中选择的语句。示例code.php:

<?php
    if ($i == 1)  // use better variable name
        print 'blah blah blah';
    else if ($i == 2)
        print 'blah blah blah';
    else if ($i == 3)
        print 'blah blah blah';
    // ...
    else if ($i == $max)
        print 'blah blah blah 4';
?>

呼叫页面:

<?php
    $max = 5;  // set max to however many statements there are
    $i = rand(1, $max);
    include('code.php');
?>

使用eval:

编辑:

或者更好的是,使用包括。这可以是if-else语句、switch语句、数组或任何可以从选项中选择的语句。示例code.php:

<?php
    if ($i == 1)  // use better variable name
        print 'blah blah blah';
    else if ($i == 2)
        print 'blah blah blah';
    else if ($i == 3)
        print 'blah blah blah';
    // ...
    else if ($i == $max)
        print 'blah blah blah 4';
?>

呼叫页面:

<?php
    $max = 5;  // set max to however many statements there are
    $i = rand(1, $max);
    include('code.php');
?>

尝试使用
htmlentities()
来转义php代码。比如:

$string = '<?php print insert_proplayer( array( "width" => "600", "height" => "400" ), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>';
echo htmlentities($string);
$string='';
回显属性($string);

尝试使用
htmlentities()
来转义php代码。比如:

$string = '<?php print insert_proplayer( array( "width" => "600", "height" => "400" ), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>';
echo htmlentities($string);
$string='';
回显属性($string);

将print语句放在php文件中,而不是txt文件中?整个方法看起来都错了,code.txt是如何生成的?为什么不改为使用?它会从你的代码中删去10行。将print语句放在一个php文件中,而不是txt?整个方法看起来是错误的,code.txt是如何生成的?为什么不改用它呢?它会从你的代码中删去10行。if和else if选项ony不是给了我2个选项,没有随机选择吗?根据你的意愿添加尽可能多的选项。这就是
/..
的意思。要随机化,请使用
$i=rand(1,$max)
,其中,
$max
是要随机化的语句数。我的答案旨在作为解决方案的模板想法,而不是解决方案本身。if和else if选项ony是否为我提供了2个选项,但没有随机选项?请添加任意多个选项。这就是
/..
的意思。要随机化,请使用
$i=rand(1,$max)
,其中,
$max
是要在其中随机化的语句数。我的答案旨在作为解决方案的模板想法,而不是解决方案本身。