php - 通过 php 的定界符本身拆分字符串

标签 php regex string

我正在尝试从一个长文件中提取 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

更新: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 来解决。 skip linbreaks 的修饰符:

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

关于php - 通过 php 的定界符本身拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821771/

相关文章:

regex - 如何使用正则表达式从 Bash 中的字符串中提取变量?

用于过滤字符串的 Javascript 正则表达式

r - 如何在 R 中优化此代码(将字符串拆分为列)

php - 如何用预言测试 Doctrine Entity Manager findOneById 方法?

javascript - 使用 JQuery、AJAX 和 PHP 提交表单

java - 当我在 groovy 中使用正则表达式替换时,如何解决 java.lang.StackOverflowError 问题?

java - 查找字符串是否唯一

php - $wpdb get_results - 从特定类别循环

php - 如何使用ajax上传图片并预览

c++ - 读取/proc/pid/status的正确方式