dongtou2016 2017-12-25 14:32
浏览 65
已采纳

仅从PHP文件中获取源代码

Is there any clean grep one-liner to grep only the PHP source (the code between <? and ?>) from a PHP file? Thus far I've tried:

grep -oiE "<\?php[[:print:]]*\?>" name_of_php_file

But it seems to return muddled entries like:

<?php print $row[0];?>"><img src="gallerybig/<?php echo $row[1];?>

Expecting a one-liner which would return only PHP source, without any muddled entries. sed and awk are OK.


EDIT: The expected output is PHP source code, even if it spans multiple lines. The sample output is bad, as it contains HTML in between: "><img src="gallerybig/


EDIT 2: The answer given by @SigmaPiEpsilon works, but grep doesn't print code that spans multiple lines. For example, this snippet of code doesn't show up in the output:

<?php 
$str="select c_id,c_description,cate_name,date from book_table ;";
$res=mysql_query($str); ?>
  • 写回答

2条回答 默认 最新

  • duanlan7903 2017-12-25 15:38
    关注

    You have to use a non-greedy search by adding a ? after the [[:print:]]*. This is not available in normal grep but available with Perl syntax by specifying -P flag instead of -E. Check man grep to make sure your grep supports this.

    $ Var='<?php print $row[0];?>"><img src="gallerybig/<?php echo $row[1];?>'
    $ echo $Var | grep -oiP "<\?php[[:print:]]*?\?>"
    <?php print $row[0];?>
    <?php echo $row[1];?>
    

    To match this over multiple lines you have to specify a newline character and use the -z flag. The regex gets a little tricky, but instead of specifying non-greedy match with ? you can use the complement match as [^?] which matches everything except ?. See below

    $ cat test_php 
    <?php 
    $str="select c_id,c_description,cate_name,date from book_table ;";
    $res=mysql_query($str); ?>
    <?php print $row[0];?>"><img src="gallerybig/<?php echo $row[1];?>
    $ grep -oizP "<\?php[^?]*
    *\?>" test_php
    <?php 
    $str="select c_id,c_description,cate_name,date from book_table ;";
    $res=mysql_query($str); ?>
    <?php print $row[0];?>
    <?php echo $row[1];?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型