我试图从一个长文件中提取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.
Run Code Online (Sandbox Code Playgroud)
我想返回一个数组:
array(
[1] => "<?php echo $user_name; ?>"
[2] => "<?php echo $datetime; ?>"
)
Run Code Online (Sandbox Code Playgroud)
我想我可以用正则表达式做到这一点,但我不是专家.有帮助吗?我用PHP写这个.:)
您必须查看源代码才能看到结果,但这就是我想出的:
$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
Run Code Online (Sandbox Code Playgroud)
更新:正如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
Run Code Online (Sandbox Code Playgroud)
另一种方法是检查<?(空格)速记php语句.你可以包含一个space(\s)来检查:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/",$string,$matches);
Run Code Online (Sandbox Code Playgroud)
我想这只取决于你想要的"严格"程度.
Update2: MikeM确实提出了一个很好的观点,即了解换行符.您可能会遇到标记运行到下一行的实例:
<?php
echo $user_name;
?>
Run Code Online (Sandbox Code Playgroud)
使用s修饰符可以很容易地解决这个问题skip linbreaks:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/s",$string,$matches);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |