[英]Replace a tag with href link
I have a html source code and want to replace all <a>
tags with its containing href link. 我有一个html源代码,并想用其包含的href链接替换所有
<a>
标记。
So the tag looks like: 因此标签看起来像:
<a href="http://google.com" target="_blank">click here</a>
I expect as output: 我期望作为输出:
http://google.com
I already tried some regex in combination with preg_replace, but none of them give me the href content. 我已经结合preg_replace尝试过一些正则表达式,但是没有一个给我href内容。
So what would be the best way to do this? 那么什么是最好的方法呢?
Match with regex <a .*href="([^"]*)".*?<\\/a>
and replace with first group using \\1
or $1
. 与正则表达式
<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";
}
The result: 结果:
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.