基于其后缀删除整个PHP函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于其后缀删除整个PHP函数相关的知识,希望对你有一定的参考价值。
我想从我的代码中删除以_example
结尾的所有函数。我正在使用token_get_all
处理代码。我目前的代码如下所示,更改开始标记并删除注释。
foreach ($files as $file) {
$content = file_get_contents($file);
$tokens = token_get_all($content);
$output = '';
foreach($tokens as $token) {
if (is_array($token)) {
list($index, $code, $line) = $token;
switch($index) {
case T_OPEN_TAG_WITH_ECHO:
$output .= '<?php echo';
break;
case T_COMMENT:
case T_DOC_COMMENT:
$output .= '';
break;
case T_FUNCTION:
// ???
default:
$output .= $code;
break;
}
} else {
$output .= $token;
}
}
file_put_contents($file, $output);
}
我根本无法弄清楚如何修改它以根据名称去除整个函数。
答案
好的,我为您的问题编写了新代码:
首先,他在源代码中找到每个函数和它们的声明。其次,他检查函数名称是否由“_example”完成并删除他的代码。
$source = file_get_contents($filename); // Obtain source from filename $filename
$tokens = token_get_all($source); // Get php tokens
// Init variables
$in_fnc = false;
$fnc_name = null;
$functions = array();
// Loop $tokens to locate functions
foreach ($tokens as $token){
$t_array = is_array($token);
if ($t_array){
list($t, $c) = $token;
if (!$in_fnc && $t == T_FUNCTION){ // "function": we register one function start
$in_fnc = true;
$fnc_name = null;
$nb_opened = $nb_closed = 0;
continue;
}
else if ($in_fnc && null === $fnc_name && $t == T_STRING){ // we check and store the name of function if exists
if (preg_match('`function\s+'.preg_quote($c).'\s*\(`sU', $source)){ // "function function_name ("
$fnc_name = $c;
continue;
}
}
}
else {
$c = $token; // single char: content is $token
}
if ($in_fnc && null !== $fnc_name){ // we are in declaration of function
$nb_closed += substr_count($c, '}'); // we count number of } to extract later complete code of this function
if (!$t_array){
$nb_opened += substr_count($c, '{') - substr_count($c, '}'); // we count number of { not closed (num "{" - num "}")
if ($nb_closed > 0 && $nb_opened == 0){ // once "}" parsed and all "{" are closed by "}"
if (preg_match('`function\s+'.preg_quote($fnc_name).'\s*\((.*\}){'.$nb_closed.'}`sU', $source, $m)){
$functions[$fnc_name] = $m[0]; // we store entire code of this function in $functions
}
$in_fnc = false; // we declare that function is finished
}
}
}
}
// Ok, now $functions contains all functions found in $filename
$source_changed = false; // Prevents re-write $filename with the original content
foreach ($functions as $f_name => $f_code){
if (preg_match('`_example$`', $f_name)){
$source = str_replace($f_code, '', $source); // remove function if her name finished by "_example"
$source_changed = true;
}
}
if ($source_changed){
file_put_contents($filename, $source); // replace $filename file contents
}
以上是关于基于其后缀删除整个PHP函数的主要内容,如果未能解决你的问题,请参考以下文章
php 在Yoast SEO中更改或删除OpenGraph输出的代码片段。此代码中有多个代码段。