0

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

1 Answer 1

3
$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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.