使用PHP的分隔符自身来分割字符串

3

我正在尝试从一个长文件中提取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编写的。:)


一个了解正则表达式的好地方是www.regular-expressions.info - jmbertucci
1个回答

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);

我想这只取决于你想要多么"严格"。 更新2:MikeM提出了一个很好的观点,即注意换行符。你可能会遇到这样的情况,即标记跨到下一行:
<?php 
echo $user_name; 
?>

这可以通过使用s修饰符来跳过换行符轻松解决:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/s",$string,$matches);

2
PHP有时也可以使用<?=这样的短标签,因此您可能希望将其添加到示例中。 - Revent
1
你可能想要添加singleline标志,这样.就可以跨越换行符匹配,即/s - MikeM
谎言断点让我困扰,太棒了,我回来评论,问题已经解决了!谢谢大家。 - user1955162

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接