Reputation: 5727
I have a variable containing anchor tags which I need to str_replace on the <a>
tags BUT the contents of the tags will change. I'm assuming regex can be used for this?
This is an example of the link.
<a href="/url?q=http://www.fandango.com/redirect.aspx%3Ftid%3DAAPOS%26tmid%3D136675%26date%3D2014-10-15%2B14:20%26a%3D11584%26source%3Dgoogle&sa=X&oi=moviesf&ii=0&usg=AFQjCNG2oI9LFx-CeZ61PNCnniNnD1XyAQ" class="fl">
I need an expression to represent <a href="{expression here}" class=fl>
I've made a few attempts but am not really sure where to start as there are special characters, numbers, letters etc.
If someone could answer it, and maybe even point to what parts do what, that would be awesome!
Thanks :)
Upvotes: 0
Views: 36
Reputation: 89547
With DOMDocument:
$dom = new DOMDocument();
@$dom->loadHTML($yourhtml);
$linkNodes = $dom->getElementsByTagName('a');
foreach ($linkNodes as $linkNode) {
if ($linkNode->getAttribute('class') == 'fl')
$linkNode->setAttribute('href', $whateveryouwant);
}
$yourhtml = $dom->saveHTML();
Upvotes: 0
Reputation: 5637
You could try something as simple as:
<a href="[^"]+" class="fl">
That should match an anchor tag with href and class attributes in that order, where the href attribute has to have a value and can contain anything but a double quote. If you don't care if the href is empty, then Avinash Raj's comment would also work:
<a href="[^"]*" class="fl">
If you need something more complex than this, add more specific requirements or false positives you want to exclude, false negatives you want to include.
Upvotes: 1