dongshuo9350 2013-01-22 10:22
浏览 54
已采纳

PHP,preg_replace,用标签attr替换标签

Can I have a detail explain about how can I replace with tag with current attr using php?

I read manual and some referencs

How to use php preg_replace to replace HTML tags

For the easy command I can understand, but for the search command on preg_replace with letters like ~, $1, /n, and etc, I dont understand at all...

If I want to replace

 <script src="core.js"></script>

into

 <temp src="library/js/core.js"></temp>

How can I implement preg_replace?

Thank you very much for your advice.

  • 写回答

2条回答 默认 最新

  • dsbiw2911188 2013-01-22 10:39
    关注

    You need to learn about regular expressions, this site is a useful resource;

    A quick example with preg_replace could be something like this - it could be improved, but hopefully will give you the idea...

    <?php
    $string = '<script src="core.js"></script>';
    $pattern = '/<script src\s?=\s?['|"](.*)['|"]><\/script>/i';
    $replace = ' <temp src="library/js/$1"></temp>';
    $result = echo preg_replace($pattern, $replace, $string);
    ?>
    

    You will need to learn about back-references in order to use matched bits of the string to create your new one. Briefly, the part of your pattern that is wrapped in parenthesis can be retrieved later with the $1 token which you include in your $replace string. You can back-reference as many times as you want this way. You can test regular expressions as you are working on them here too, hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图