我有一个html源代码,并且想用其包含href链接替换全部<a>
标记。用href链接替换标记
所以标签的样子:
<a href="http://google.com" target="_blank">click here</a>
我期望的那样输出:
http://google.com
我已经尝试了一些正则表达式结合了preg_replace, 但没有人给我的href内容。
那么最好的方法是什么?
我有一个html源代码,并且想用其包含href链接替换全部<a>
标记。用href链接替换标记
所以标签的样子:
<a href="http://google.com" target="_blank">click here</a>
我期望的那样输出:
http://google.com
我已经尝试了一些正则表达式结合了preg_replace, 但没有人给我的href内容。
那么最好的方法是什么?
与正则表达式匹配<a .*href="([^"]*)".*?<\/a>
并用\1
或$1
替换为第一组。
<?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
这将不会完全匹配,直到''标签的末尾。 –
它不需要。非贪婪的搜索'(。*?)''会在匹配结束引号时停止匹配。 –
但是它必须**替换**洞''标记。 PS:没有倒选票。有人试图赢得他的“选举权”徽章:D –
看起来像一个串行下来选民今天失去。 –
哟!这个答案完美地工作 – ForJ9