你需要查看源代码才能看到结果,但这是我想出的:
$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]);
print_r($matches[1]);
更新:如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]);
print_r($matches[1]);
另一种选择是检查带有空格的
<?
,这是php简写语句。您可以包含一个空格(
\s
)来检查此内容:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/",$string,$matches)
我想这只取决于你想要多么"严格"。
更新2:
MikeM提出了一个很好的观点,即注意换行符。你可能会遇到这样的情况,即标记跨到下一行:
<?php
echo $user_name;
?>
这可以通过使用
s
修饰符来
跳过换行符
轻松解决:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/s",$string,$matches)