John S
John S

Reputation: 59

Use preg_match() and replace to converting URL to anchor tag in text

I currently have the following code to add an a href to user-submitted plain text where HTTPS:// is found. The problem is that this obviously changes all links in the text to the same name/location. How can I do this process seperately for every instance of HTTPS:// in the text?

//Example variables (usually from MySQL)
$moreOrig = "https://duckduckgo.com is better than https://google.com";
// The Regular Expression filter
$testUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

if (preg_match($testUrl, $moreOrig, $url)) {
//split into parts if user has a /something to clean url
    $parts = explode ("/", $url[0]);

    //glue
    list($first, $second, $third) = $parts;

    //output
    $shortUrl = implode ("/", array($third));

    $more = nl2br(preg_replace($testUrl, "<a href='" . $url[0] . "' rel = 'nofollow'>" . $shortUrl . "</a>", $moreOrig));
  }

Output, desired vs actual ( assume input variable = "https://duckduckgo.com?q=Duck+Duck+Go is better than https://google.com?q=Duck+Duck+Go")

Desired:
<a href = "https://duckduckgo.com?q=Duck+Duck+Go">duckduckgo.com</a> is better than <a href = "https://google.com?q=Duck+Duck+Go">google.com.</a>
<br>
Actual:
<a href = "https://duckduckgo.com?q=Duck+Duck+Go">duckduckgo.com</a> is better than <a href = "https://google.com?q=Duck+Duck+Go">google.com.</a>

Upvotes: 0

Views: 1372

Answers (3)

ChunkyBarsEater
ChunkyBarsEater

Reputation: 66

<?php declare(strict_types = 1);

$input = "
xxx
https://duckduckgo.com/url/foo
xxx
https://bing.com
xxx
https://google.com/
xxx
";

$result = preg_replace_callback(
    "@
        (?:http|ftp|https)://
        (?:
            (?P<domain>\S+?) (?:/\S+)|
            (?P<domain_only>\S+)
        )
    @sx",
    function($a){
        $link = "<a href='" . $a[0] . "'>";
        $link .= $a["domain"] !== "" ? $a["domain"] : $a["domain_only"];
        $link .= "</a>";
        return $link;
    },
    $input
);

echo $result;

Upvotes: 4

Mohammad
Mohammad

Reputation: 21489

You does not need to use preg_match(), explode() and implode(). Just use preg_replace(). You need to use a group match for whole of url to replacing it by <a></a>

$testUrl = "@((https?|ftps?)://([\w\-.]+\.[a-zA-Z]{2,3})(/\S*)?)@";
$newStr = preg_replace($testUrl, "<a href='$1'>$3</a>", $moreOrig);

Check result in demo

Upvotes: 0

Smuuf
Smuuf

Reputation: 6534

You can do this easily with preg_replace_callback.

<?php

//Example variables (usually from MySQL)
$string = "https://duckduckgo.com is better than https://google.com";

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

$result = preg_replace_callback($pattern, function($match) {
    $url = $match[0];
    return sprintf('<a href="%1$s">%1$s</a>', $url);
}, $string);

// Result:
// "<a href="https://duckduckgo.com">https://duckduckgo.com</a> is better than <a href="https://google.com">https://google.com</a>"

Upvotes: 0

Related Questions