用href链接替换标记


Replace a tag with href link

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

所以标签看起来像:

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

我期望输出:

http://google.com

我已经尝试了一些regex与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