Zabs Zabs - 1 year ago 92
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 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.

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

Answer Source
$message = preg_replace("/<a([^>]+)href=\"http\:\/\/([a-zA-Z0-9\-]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/[^\"]*)?)/", "<a$1href=\"$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=\"$2&ID={$ID}\"", $message);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download