Search code examples
phpregexreplacehtml-parsing

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!


Solution

  • Use this:

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