2013-04-04 127 views
3

我想从一个长文件中提取php代码。我希望丢弃不在PHP标签中的代码。例如由php的分隔符本身分割一个字符串

<html>hello world, its a wonderful day</html> 
<?php echo $user_name; ?> Some more text or HTML <?php echo $datetime; ?> 
I just echoed the user_name and datetime variables. 

我想与返回数组:

array(
    [1] => "<?php echo $user_name; ?>" 
    [2] => "<?php echo $datetime; ?>" 
) 

我想我能做到这一点与正则表达式,但即时通讯不是专家。任何帮助?我用PHP写这篇文章。 :)

+0

一个伟大的地方开始学习正则表达式是[www.regular-expressions.info](http://www.regular-expressions.info/)。 – jmbertucci 2013-04-04 21:19:59

回答

7

你将不得不才能看到的结果,查看源代码,但是这是我想出了:

$string = '<html>hello world, its a wonderful day</html> 
<?php echo $user_name; ?> Some more text or HTML <?php echo $datetime; ?> 
I just echoed the user_name and datetime variables.'; 

preg_match_all("/<\?php(.*?)\?>/",$string,$matches); 

print_r($matches[0]); // for php tags 
print_r($matches[1]); // for no php tags 

更新:正如Revent提到的,你可以有<?=简写回声统计。这将有可能改变你的preg_match_all包括此:

$string = '<html>hello world, its a wonderful day</html> 
<?php echo $user_name; ?> Some more text or HTML <?= $datetime; ?> 
I just echoed the user_name and datetime variables.'; 

preg_match_all("/<\?(php|=)(.*?)\?>/",$string,$matches); 

print_r($matches[0]); // for php tags 
print_r($matches[1]); // for no php tags 

另一种方法是检查<?(空间)的简写PHP语句。您可以包括一个空间(\s)检查此:

preg_match_all("/<\?+(php|=|\s)(.*?)\?>/",$string,$matches); 

我想这只是取决于如何“严”,你想要的。

Update2:MikeM确实很好,关于意识到换行符。您可能会遇到在您的标签运行在进入下一行实例:

<?php 
echo $user_name; 
?> 

这可以很容易地通过使用s改性剂skip linbreaks解决:

preg_match_all("/<\?+(php|=|\s)(.*?)\?>/s",$string,$matches); 
+2

PHP有时也可以使用短标签,如<?=,所以您可能想添加到您的示例中。 – Revent 2013-04-04 21:20:50

+0

谢谢!我现在正在尝试... – user1955162 2013-04-04 21:51:18

+1

您可能想要添加单行标记,以便在换行符之间匹配'.',即'/ s'。 – MikeM 2013-04-04 21:56:31