用PHP和preg_replace拆分并替换事物,而不是爆炸? [英] Split and replace things with PHP and preg_replace instead of explode?

查看:43
本文介绍了用PHP和preg_replace拆分并替换事物,而不是爆炸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP + HTML代码作为包含函数的字符串.我希望将某些函数调用替换为包含的内容.将许多文件放在一起.

I have a PHP + HTML code as a string containing functions. I want some function calls to be replaced with included content. Put together many files to one.

简短示例-之前

<html>
    <?php myclass->my_function('one', 'two', 'three'); ?>
    <h1>Content in between</h1>
    <?php myclass->my_function('1', '2'); ?>
</html>

简短示例-替换内容

<html>
    <?php run('one', 'two', 'three'); /* Run does include a file */ ?>
    <h1>Content in between</h1>
    <?php run('1', '2'); /* Run does include a file */ ?>
</html>`

简短示例-之后

<html>
    <?php
    /* Start my_function */
        echo 'This is the result of my_function one two three';
    /* End my_function
    ?>
    <h1>Content in between</h1>
    <?php
    /* Start my_function */
        <?php myclass->my_function('four', 'five', 'six'); ?>
    /* End my_function
    ?>
</html>

请注意,在包含的内容中找到了myclass.结果需要再次解析.

Notice that myclass is found in the included content. The result needs to be parsed again.

简短示例-之后

整个过程再次被解析,并用包含的内容替换了myclass.

The whole this is parsed again and it replaced the myclass with included content.

<html>
    <?php
    /* Start my_function */
        echo 'This is the result of my_function one two three';
    /* End my_function */
    ?>
    <h1>Content in between</h1>
    <?php
    /* Start my_function */
        echo 'four five six';
    /* End my_function */
    ?>
</html>

我试图用爆炸来做到这一点,但是事情变得复杂了.替换内容"和之后"这两个步骤可能需要一步完成.

I tried to do this with explode but it went to complex. The two steps "Replacing content" and "After" might need to be done in one move.

将其视为字符串.preg_replace可以解决这个问题吗?怎么样?

Look at it as a string. Can preg_replace solve this? How?

推荐答案

$str = '<html>
<?php myclass->my_function(\'styles\', \'home.css\'); ?>
<p>Some other content</p>
<?php myclass->my_function(1, 2, 3); ?>
</html>';

function jens($matches)
{ 
    $path = '';
    $parts = explode(',', $matches[1]);
    foreach($parts as $match)
        $path .= '/' . str_replace('\'', '', trim($match));

    return $path;
}

$replaced = preg_replace_callback('/<\?php myclass->my_function\((.*?)\); \?>/', 'jens', $str);

echo $replaced;

应该做你想做的事.

这篇关于用PHP和preg_replace拆分并替换事物,而不是爆炸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆