使用php's分隔符拆分字符串


Split a string by php's delimiters itself

我正试图从长文件中提取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写的。:)

您必须查看源代码才能看到结果,但这是我想到的:

$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

Update:如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);