Zabs Zabs - 29 days ago 6
PHP Question

Convert all html links to another URL with PHP & Regex

I am trying get all html links within a string and replace them using preg_replace to another link (for link tracking etc)

It works fine on links like http://www.facebook.com but not those that have any extra text after the domain extension
So the first URL would be fine, but the latter wouldn't work - can anyone suggest how I alter my expression to allow BOTH links like this to work.

http://www.facebook.com
http://www.facebook.com/profile/1242435

$message = preg_replace("/<a([^>]+)href=\"http\:\/\/([a-zA-Z0-9\-]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/*)?)/", "<a$1href=\"http://www.site.com/system/link_tracker.php?URL=$2&ID={$ID}\"", $message);

Answer
$message = preg_replace("/<a([^>]+)href=\"http\:\/\/([a-zA-Z0-9\-]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/[^\"]*)?)/", "<a$1href=\"http://www.site.com/system/link_tracker.php?URL=$2&ID={$ID}\"", $message);

Like this? By the way, domain zone can be longer than 3 symbols. And you can make it a little shorter with flag /i

$message = preg_replace("/<a([^>]+)href=\"http\:\/\/([a-z\d\-]+\.[a-z\d]+\.[a-z]{2,5}(\/[^\"]*)?)/i", "<a$1href=\"http://www.site.com/system/link_tracker.php?URL=$2&ID={$ID}\"", $message);