【问题标题】:Parsing Out Code Between Comment Blocks PHP解析注释块之间的代码 PHP
【发布时间】:2012-01-21 02:14:07
【问题描述】:

假设我在 PHP 文件中有以下开头部分:

/**
 * @SomethingStart
 */
protected static $var1 = '1';
protected static $var2 = '2';
protected static $var3 = '3';
/**
 * @SomethingEnd
 */

我试图弄清楚如何首先使用 @SomethingStart 和 @SomethingEnd 解析出 cmets 之间的内容(不包括评论,其次,如何替换这两个标签之间的内容。

【问题讨论】:

  • 你可以使用preg_replace_all

标签: php code-generation phpdoc


【解决方案1】:

可以通过函数获取文件内容:

file 

http://www.php.net/manual/en/function.file.php

返回一个行数组。然后就可以使用foreach,将行内容与

匹配
$switch = false; 
$lines = file('filepath');
$string = '';
foreach($lines as $k => $v)
{
    if(preg_match('/@(.*)End$/'. $v))
    {
        $switch = false;
        break;
    }
    if($switch == true)
    {
        // do replacements, or anything you want with the following lines
        // or add, or remove, even if you might have some problems with it
        // for this you might not consider using foreach, instead you might
        // try array_walk
    }
    if(preg_match('/@(.*)Start$/', $v))
    {
        $switch = true;
    }


    $string .= $v;
}

echo $string;

对于array_walk,请阅读http://www.php.net/manual/en/function.array-walk.php

试试看。

【讨论】:

  • 也许开始行和结束行的 preg_match 应该在实际处理这些行之前进行,以免意外将它们编辑掉。
  • 我已经编辑了我的答案,对 end 的测试必须在之前,并且在 end 的测试中,在 foreach 逻辑中,当它遇到停止命令时它会中断,并且在对方只有在启动命令之后的步骤才会开始修改东西。
  • 谢谢,这正是我所需要的(针对我的特殊情况稍作调整)
猜你喜欢
  • 2011-01-28
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 2010-11-07
  • 1970-01-01
  • 2013-04-07
  • 2012-03-13
相关资源
最近更新 更多