Zabs
Zabs

Reputation: 14142

Simplest way to convert all html links in a string using PHP

I am trying to convert a block of text that contains html text - i'd like to find all http links and convert them for link tracking purposes.

So eg anything like this in a string would be converted to the latter

<a href="http://www.google.com">Some Link</a>

<a href="http://www.mysite.com/tracking.php?url=www.google.com">Some Link</a>

Can anyone how to do this taking into account the original string will consists of all sorts of html, images etc..

Upvotes: 0

Views: 272

Answers (2)

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Use this regex : (UPDATED)

<?php

$str = '<h1>Page Title</h1><a href="http://www.google.com/">Google</a>';
$text = preg_replace("/href=\"http\:\/\/([a-zA-Z0-9\-]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/*)?)/","href=\"http://www.mysite.com/tracking.php?url=$1\"",$str);

echo $text;

?>

Outputs :

<h1>Page Title</h1><a href="http://www.mysite.com/tracking.php?url=www.google.com/"">Google</a>

Upvotes: 2

Zabs
Zabs

Reputation: 14142

$str = '<h1>Page Title</h1><a href="http://www.google.com">Google</a>';
$text = preg_replace('href=\"http\://([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?)\"', 'href=\"YOUR_TRACKING_URL=$1\"', $str);
echo $text;

Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in /home/.... (sorry for the duplication)

Upvotes: 0

Related Questions