如果你的<?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>