I have 2 regex questions related to hyperlinks:
1. I am trying to add a class to hyperlinks with a certain URL. What I have now is this:
$pattern = "/<a href=[\'\"](" . $url . ")[\'\"]>(.*)<\/a>/is";
$replace = "<a href=\"$1\" class=\"". $class_name ."\">$2</a>";
$html = preg_replace($pattern, $replace, $html);
But this only works if the original <a> tag has no special attributes, such as an id, style, target, title or another class.
If it already has a class I want to replace it with my new class.
2. To find all hyperlinks in a text I am using the following preg_match_all:
preg_match_all(
'#<a\s
(?= [^>]* href=" (?P<href> [^"]*) ")|)
(??= [^>]* title=" (?P<title> [^"]*) ")|)
(??= [^>]* class=" (?P<class> [^"]*) ")|)
(??= [^>]* target=" (?P<target>[^"]*) ")|)
[^>]*>
(?P<text>[^<]*)
</a>
#xi',
$html,
$matches,
PREG_SET_ORDER
);
This works well, but it doesn't find links with single quotes. So it'll find <a href="something"> but not <a href='something'>
Can someone help me with this? I have been struggling with this for a while. Thank you.