【问题标题】:How to replace "a" tag with "img" using regex in php? [duplicate]如何在php中使用正则表达式将“a”标签替换为“img”? [复制]
【发布时间】:2016-11-19 03:35:31
【问题描述】:
<div class="media_embed" height="qqq" width="www">
<a href="http://giphy.com/gifs/dancing">via GIPHY</a>
<div class="media_embed" height="eee" width="rrr">
<a href="http://giphy.com/gifs/movie">via GIPHY</a>

我想这样做: 我必须从锚标签中获取 de href 并将其放在 img 标签之间并添加 figure 标签

<figure>
  <img src="http://giphy.com/gifs/dancing" />
</figure>
<figure>
  <img src="http://giphy.com/gifs/movie" />
</figure>

你能帮帮我吗

【问题讨论】:

  • 不要使用正则表达式,使用解析器。
  • 请标记我的回答以完成本次讨论。

标签: php html regex anchor href


【解决方案1】:

最好的解决方案是解析html,然后改变它。您可以使用DOMDocument 来解析html。但是如果要使用正则表达式,请使用preg_replace()a 标签替换为另一个标签。

echo preg_replace("/<a href=\"(.*)\">.*<\/a>/", "<figure><img src='$1' /></figure>", $html)

demo查看结果

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多