繁体   English   中英

用href链接替换标签

[英]Replace a tag with href link

我有一个html源代码,并想用其包含的href链接替换所有 <a>标记。

因此标签看起来像:

<a href="http://google.com" target="_blank">click here</a>

我期望作为输出:

http://google.com

我已经结合preg_replace尝试过一些正则表达式,但是没有一个给我href内容。

那么什么是最好的方法呢?

与正则表达式<a .*href="([^"]*)".*?<\\/a>匹配,并使用\\1$1替换为第一组。

Regex101演示

<?php
$text = '
  Random text <a href="foobar.html">Foobar</a> More Text
  Other text <a href="http://www.example.com">An example</a>
  Still more text <a href="http://www.example.com/foo/bar.html">A deep link</a>. The end.
';

preg_match_all('/<a href="(.*?)"/i',$text,$matches);
foreach ($matches[1] as $match) {
    print "A link: $match\n";
}

结果:

A link: foobar.html
A link: http://www.example.com
A link: http://www.example.com/foo/bar.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM