doudong7256 2014-03-17 11:26
浏览 32
已采纳

PHP - 正则表达式改变'周围'标签

I have a piece of UTF-8 encoded HTML that I need to get one file reference out of, then I need to change it entirely using said file reference.

This is the starting code:

<object width="250" height="20" data="player.swf" type="application/x-shockwave-flash">
<param name="data" value="player.swf" />
<param name="flashvars" value="file=TEST.MP3" />
<param name="src" value="player.swf" />
</object>

As you can see, it's an object tag that contains a reference to a file, and a flash player.

This is the code that I require:

<p><a href="TEST.MP3">TEST.MP3</a></p>

I've tried getting the file reference out first, then just replacing the object part entirely with an a tag, but this just replaces all object tags and not just the one I need.

The easiest way would be ofcourse to just 'replace' the object tag with an a tag, but I don't know how to do a Regex to find and replace everything 'around' the file you need.

What would be the best way to do this?

  • 写回答

1条回答 默认 最新

  • dongyan7988 2014-03-17 12:01
    关注

    If you know that the surrounding code will be the same in all future cases and only the TEST.MP3 changes you could use the following RegEx that I've tested:

    <?php
    header('Content-type: text/plain');
    $test = '<object width="250" height="20" data="player.swf" type="application/x-shockwave-flash">
    <param name="data" value="player.swf" />
    <param name="flashvars" value="file=TEST.MP3" />
    <param name="src" value="player.swf" />
    </object>';
    
    echo preg_replace('/^\<object.*
    .*
    .*file\=(.*)\".*
    .*
    .*/mi','<a href="$1">$1</a>',$test);
    
    ?>
    

    This is working in PHP 5.3.10.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解