使用PHP
如何在某些php code
内的所有php file
中发表评论
例如,如果我有以下文件
$file = 'myfile.php';
只有PHP代码
<?php
$c = 'anything';
echo $c;
?>
我想使用PHP来评论(在关闭标签/*
之前的开放标签<?php
和*/
之后添加?>
)
<?php
/*
$c = 'anything';
echo $c;
*/
?>
还有如何反过来注释(删除/* */
)返回
<?php
$c = 'anything';
echo $c;
?>
我一直在考虑使用array_splice
然后使用str_replace
然后使用implode
和file_put_contents
,但仍然无法弄清楚如何做到这一点。
更新
好的,同时在这里得到一些帮助,我正在思考它,我想到了这个想法....使用阵列!
在打开标签/*
之后添加块注释<?php
我将该文件的内容转换为数组
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
然后我可以用array push
在2
位置/*
新元素
并做反过来我将使用unset($contents[1]);
取消位置2
元素,这意味着,/*
将消失
稍后我可以file_put_contents($file, $contents);
再次重写文件。
我不知道你为什么要评论或取消注释PHP代码,但我认为这不是一个好方法。我建议你使用变量或常量,如下所示:
另一种启用或禁用代码的方法是在第二次使用后使用常量变量:
你将能够做到:
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
<?php
function uncomment_header($name, $value) {
return '<?php define("' . $name . '", ' . $value . '); ?>';
}
function uncomment($file_path, $name) {
$current = file_get_contents($file_path);
$regex = '/<\\?php define\\("' . $name . '", (0|1)\\); \\?>/';
if (preg_match($regex, $current, $match)) {
$value = ($match[1] == 1) ? 0 : 1;
$current = preg_replace($regex, uncomment_header($name, $value), $current);
} else {
$header = uncomment_header($name, 1) . "\n";
$start = 'if (' . $name . '):';
$end = 'endif;';
$current = $header . $current;
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', $start . '$1' . $end, $current);
}
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php", "MYENV_DEBUG");
?>
PHP中有两种类型的注释1)单行注释2)php中的单个注释的多行注释我们只是键入//或者#右边的所有文本将被PHP解释器忽略。例如
<?php
echo "code in PHP!"; // This will print out Hello World!
?>
结果:PHP代码!
对于多行注释,多行PHP注释以“/ *”开头,例如以“/”结尾
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Noman Ali!";
echo "PHP Programmer!";
*/?>
结果:Hello World!
像这样:
#canned test data, a string and the file contents are the same
$contents = <<<'CODE'
<?php
$c = 'anything';
echo $c;
?>
CODE;
$contents = preg_replace(['/<\?php\s/','/\?\>/'], ['<?php/*', '*/?>'], $contents);
echo $contents;
产量
<?php/*
$c = 'anything';
echo $c;
*/?>
注意 - 这仅在结束标记存在时才有效。在PHP中,结束标记实际上是可选的。这也不适用于短标签<?
或<?=
之类的东西,尽管它会捕捉结束标签。
由于这些边缘情况,使用正则表达式(或任何字符串替换)非常困难。
PHP代码的有效示例
<?php
$c = 'anything';
echo $c;
?>
//-------- no ending tag ---------
<?php
$c = 'anything';
echo $c;
//------- short tags ---------
<? echo 'foo'; ?>
//------- short echo tags ---------
<?= $foo; ?>
etc...
祝你好运,如果你想要抓住它们......