Reputation: 3675
similar to this question:
preg_match to extract mailto on anchor
but I am trying to do a global string replace in php that will convert:
..href="mailto:[email protected]">Mailme<... (including the "a" tags)
to only "[email protected]" with no tags. This needs to be a replace, not an extract.
I have been using preg_replace, but like so many others, am rather poor at regex. It's the regex I'm really after, but best practice is welcome as long as the final solution is clear.
Thanks!
Upvotes: 0
Views: 1860
Reputation: 39679
following regex will do work for you.
preg_replace(/<a .*?href=((?:\'|\"))mailto:(.*?)$1[^>]*>[^<]+</a>/i, "$2", $html);
use [^<]+ between start and end tag because some it may happened that line breaks occur in html, so .* will fail there, [^<]+ this fail in rare case when (less than sign) < appears in tag content. Used flag "i" for in-case sensitivity replace.
Upvotes: 0
Reputation: 50976
<?php
$html = '<a href="mailto:[email protected]">Mailme</a> (including the "a" tags)';
$html = preg_replace("~<a .*?href=[\'|\"]mailto:(.*?)[\'|\"].*?>.*?</a>~", "$1", $html);
echo $html;
Upvotes: 1