Reputation: 47
I am trying to do this regex match and replace but not able to do it.
Example
<a href=one target=home>One</a>
<a href=two>Two</a>
<a href=three target=head>Three</a>
<a href=four>Four</a>
<a href=five target=foot>Five</a>
I want to find each set of the a tags and replace with something like this
Find
<a href=one target=home>One</a>
Change to
<a href='one'>One</a>
same way the the rest of the a tags.
Any help would be very appreciated!
Upvotes: 1
Views: 5880
Reputation: 5856
Use this:
preg_replace('/<a(.*)href=(")?([a-zA-Z]+)"? ?(.*)>(.*)<\/a>/', '<a href='$3'>$5</a>', '{{your data}}');
Upvotes: 1
Reputation: 8118
if you want a regex, try this:
$str = preg_replace('/<a [^>]*href=([^\'" ]+) ?[^>]*>/',"<a href='\1'>",$str);
I don't recommend using a regular expression to do this though.
Upvotes: 0
Reputation: 219814
Using DomDocument()
would be an easier way to work with HTML.
<?php
$str = '<a href=one target=home>One</a>
<a href=two>Two</a>
<a href=three target=head>Three</a>
<a href=four>Four</a>
<a href=five target=foot>Five</a>';
$dom = new DomDocument();
$dom->loadHTML($str);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $a)
{
if ($a->hasAttribute('target'))
{
$a->removeAttribute('target');
}
}
$str = $dom->saveHTML();
Upvotes: 5