Rip Hunter
Rip Hunter

Reputation: 97

PHP Replace multiple URL's in text with anchor tags

I have tried following so far:

<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       $final = preg_replace($reg_exUrl, "<a href=\"{$url[0]}\">{$url[0]}</a> ", $text);

       echo $final;

} else {
       // if no urls in the text just return the text
       echo $text;
}

The only issue I am facing is that this is replacing both the URL's with the same url(that is the one found first). How do I loop this to replace each url with their own?

Upvotes: 1

Views: 1781

Answers (2)

HamZa
HamZa

Reputation: 14921

Just use a single preg_replace():

$url_regex = '~(http|ftp)s?://[a-z0-9.-]+\.[a-z]{2,3}(/\S*)?~i';

$text = 'The text I want to filter is here. It has urls https://www.example.com and http://www.example.org';

$output = preg_replace($url_regex, '<a href="$0">$0</a>', $text);

echo $output;

In the replace part, you can refer to groups that were matched by using $0, $1 etc... Group 0 is the whole match.

Another example:

$url_regex = '~(?:http|ftp)s?://(?:www\.)?([a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?)~i';

$text = 'Urls https://www.example.com and http://www.example.org or http://example.org';

$output = preg_replace($url_regex, '<a href="$0">$1</a>', $text);

echo $output;

// Urls <a href="https://www.example.com">example.com</a> and <a href="http://www.example.org">example.org</a> or <a href="http://example.org">example.org</a>

Using a preg_match() doesn't make sense, regex invocations are relatively expensive performance wise.

PS: I also tweaked your regex a bit along the way.

Upvotes: 5

Chetan Ameta
Chetan Ameta

Reputation: 7896

try this:

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

    // make the urls hyper links
    $final = preg_replace($reg_exUrl, '<a href="$0">$0</a>', $text);

    echo $final;

} else {
    // if no urls in the text just return the text
    echo $text;
}

output:

The text I want to filter is here. It has urls <a href="http://www.example.com">http://www.example.com</a> and <a href="http://www.example.org">http://www.example.org</a>

Upvotes: 2

Related Questions