SchizoBoy
SchizoBoy

Reputation: 47

PHP regex - find and replace link

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

Answers (3)

worenga
worenga

Reputation: 5856

Use this:

preg_replace('/<a(.*)href=(")?([a-zA-Z]+)"? ?(.*)>(.*)<\/a>/', '<a href='$3'>$5</a>', '{{your data}}');

Upvotes: 1

StampyCode
StampyCode

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

John Conde
John Conde

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();

See it in action

Upvotes: 5

Related Questions