PHP写入文件减去PHP代码?

时间:2011-11-24 23:17:26

标签: php text strpos

我想将文件写入文件,该文件包含一些PHP代码。当有人读取文件时,我不希望该文件运行PHP。基本上,我想要<?php?>之间的所有文字以及这些标签。有没有办法在PHP中这样做?可能与strpos?我试着用strpos;但我无法理解。

以下是一个例子:

<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is what I want written to a file!</p>
</html>

3 个答案:

答案 0 :(得分:7)

最简单的方法可能是使用token_get_all解析文件,遍历结果并丢弃不属于T_INLINE_HTML类型的所有内容。

答案 1 :(得分:1)

如果您可以选择要写入的文件名,则可以写入.phps文件,该文件不会被评估为PHP。如果访问者查看.phps页面,它们将被提供一个纯文本文件,其中包含<?php ?>标记内的所有内容以及HTML。

答案 2 :(得分:1)

如果你的<?php ?>标签总是放在输入文件的顶部,你就可以爆炸输入并将标签周围的所有内容写入输出:

输入:

<?php echo "This is the PHP I want removed!"; ?>
<html> 
    <p>This is what I want written to a file!</p> 
</html>

代码:     

$inputTxt = file_get_contents($path . $file , NULL, NULL);

$begin = explode("<?php", $inputTxt);
$end = explode('?>', $inputTxt);
fwrite($output,  $begin[0] . $end[1] . "\n\n");
?>

输出:

<强>之前

<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is what I want written to a file!</p>
</html>

<强>后

<html>
<p>This is what I want written to a file!</p>
</html>

但是,如果您计划拥有多套<?php ?>代码,那么您需要使用preg_match:

输入:

<?php
echo "This is the PHP I want removed!";
?>
<html>
    <p>This is <?php echo $something; ?> I want written to a file!</p>
</html>

代码:

<?php
$file="input.txt";
$path='C:\\input\\';
$output = fopen($path . "output.txt",'w');

$inputTxt = file_get_contents($path . $file , NULL, NULL);

$pattern = '/<\?php.+\?>/isU';
$replace = '';

$newInput = preg_replace($pattern, $replace, $inputTxt);

fwrite($output,  $newInput);
?>

输出:

<强>之前

<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is <?php echo $something; ?> I want written to a file!</p>
</html>

<强>后

<html>
<p>This is  I want written to a file!</p>
</html>