I have a html source code and want to replace all <a>
tags with its containing href link.
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.
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
.
<?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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.