Convert URLs to Clickable Links Using JavaScript And PHP


When sharing text-based content online, URLs often appear as plain text, making them inaccessible for direct clicking. Manually adding anchor tags to every link can be tedious. Fortunately, both JavaScript and PHP offer solutions to automatically detect and convert raw URLs into clickable hyperlinks.

This article provides Convert URLs to Clickable Links Using JavaScript And PHP.

Example

Suppose you have the following plain text paragraph:

Visit our website for more tools: https://www.html-code-generator.com/

After applying JavaScript, the output will be:

Visit our website for more tools: <a href="https://www.html-code-generator.com/" target="_blank">https://www.html-code-generator.com</a>

JavaScript can instantly process and convert URLs on the client-side without reloading the page. This is useful for real-time applications like chat systems, comment sections, and interactive web pages.

Demo: Convert Plain Text URLs into Clickable HTML Links Online

Simply enter your text in the textarea, click the "Convert" button, and instantly transform plain text URLs into clickable HTML links.

Convert

Why Convert URLs to Clickable Links?

  • Enhances user experience by allowing direct clicks on links.
  • Saves time by automating the conversion process.
  • Ensures better readability and functionality in text-based content such as chat messages, comments, or user-generated content.
  • Works dynamically on the frontend (JavaScript) or during content processing on the backend (PHP).

JavaScript Function to Convert Plain Text URLs into Clickable Links

Use this JavaScript function to automatically detect and convert plain text URLs into clickable HTML links.

JavaScript
const convert_url = (text, link_attributes_obj = {}) => {
    // Validate inputs
    if (typeof text !== 'string') {
        return "Input text must be a string'";
    }
    if (typeof link_attributes_obj !== 'object' || link_attributes_obj === null) {
        return "Link attributes must be an object";
    }

    // Escape HTML to prevent injection issues
    text = text.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

    // Convert link_attributes_obj into valid HTML attributes, excluding 'href'
    const attr = Object.entries(link_attributes_obj)
        .filter(([key]) => key !== "href")
        .map(([key, value]) => `${key}="${value.replace(/"/g, "'")}"`)
        .join(" ");

    // URLs starting with http://, https://, or ftp://
    const urlPattern = /((?:https?|ftp):\/\/[a-zA-Z0-9][\w\d&@\-#\/%?=~_|!:,.;+]*)/gi;
    text = text.replace(urlPattern, (match) => `<a href="${encodeURI(match)}" ${attr}>${match}</a>`);

    // URLs starting with www. (avoiding cases where it's part of another URL)
    const wwwPattern = /(?<!\/)(www\.[a-zA-Z0-9][\w\d&@\-#\/%?=~_|!:,.;+]*)/gi;
    text = text.replace(wwwPattern, (match) => `<a href="https://${encodeURI(match)}" ${attr}>${match}</a>`);

    // Email addresses (basic pattern)
    const emailPattern = /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/gi;
    text = text.replace(emailPattern, (match) => `<a href="mailto:${encodeURI(match)}" ${attr}>${match}</a>`);
    // next pattern

    return text;
};

Usage:

JavaScript
// Simple usage
const result1 = convert_url("Some txt here, Visit https://www.html-code-generator.com");
console.log(result1);
document.body.innerText = result1+"\n\n";

// With attributes
const result2 = convert_url("Some txt here, Visit https://www.html-code-generator.com", {
    target: "_blank",
    class: "link",
    rel: "noopener noreferrer"
});
console.log(result2);
document.body.innerText += result2;

Example with HTML code:

HTML
<textarea rows="10" cols="75" id="input">Online HTML Code Generator CSS, JavaScript, PHP, JQuery, https://www.html-code-generator.com/  Multi Color Text Generator www.html-code-generator.com/html/rainbow-text-generator </textarea>
<button id="convert">Convert</button>
<p id="preview-text"></p>

<script>
	const button = document.getElementById("convert");
	const input = document.getElementById("input");
	const result = document.getElementById("preview-text");

	button.addEventListener("click", function(){
	  	const text = input.value;
		const link_attributes = {
			target: '_blank',
			class: 'mylink',
			rel: 'nofollow noopener'
		};
	  	result.innerHTML = convert_url(text, link_attributes);
	});
</script>

Optional Enhancements: Convert Phone Numbers, Twitter Handles, and Hashtags

Extend the functionality by converting phone numbers, Twitter usernames, and hashtags into clickable links. This feature enhances user engagement by enabling quick access to phone calls, Twitter profiles, and hashtag searches.

Convert Phone Numbers to Clickable Links

Automatically detect phone numbers in text and convert them into clickable tel: links for quick dialing.

JavaScript
// Phone numbers (tel: by default)
const phonePattern = /(\+?\d{1,4}[\s.-]?\d{3,4}[\s.-]?\d{4,6})/g;
text = text.replace(phonePattern, (match) => `<a href="tel:${match}" ${attr}>${match}</a>`);

Convert Twitter Handles (@username) to Profile Links

Detect Twitter usernames in text and link them to their corresponding Twitter profiles.

JavaScript
// Twitter handles (@username) → Links to Twitter profile
const twitterPattern = /(^|\s)@([a-zA-Z0-9_]+)/g;
text = text.replace(twitterPattern, (match, space, username) => 
	${space}<a href="https://twitter.com/${username}" ${attr}>@${username}</a>`);

Convert Hashtags (#hashtag) to Twitter Search Links

Convert hashtags into clickable links that direct users to Twitter's hashtag search results.

JavaScript
// Hashtags (#hashtag) → Links to Twitter hashtag search
const hashtagPattern = /(^|\s)#([a-zA-Z0-9_]+)/g;
text = text.replace(hashtagPattern, (match, space, hashtag) => 
    `${space}<a href="https://twitter.com/hashtag/${hashtag}" ${attr}>#${hashtag}</a>`);

PHP Function to Convert Plain Text URLs into Clickable Links

Use this PHP function to automatically detect and convert plain text URLs into clickable HTML links.

PHP
<?php
function convert_url($text, $link_attributes_obj = []) {
    // Validate inputs
    if (!is_string($text)) {
        return "Input text must be a string";
    }
    if (!is_array($link_attributes_obj)) {
        return "Link attributes must be an array";
    }

    // Escape HTML to prevent injection issues
    $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

    // Convert link_attributes_obj into valid HTML attributes, excluding 'href'
    $attr = "";
    foreach ($link_attributes_obj as $key => $value) {
        if ($key !== "href") {
            $attr .= sprintf(' %s="%s"', htmlspecialchars($key, ENT_QUOTES, 'UTF-8'), htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
        }
    }

    // URLs starting with http://, https://, or ftp://
    $text = preg_replace_callback(
        '/((?:https?|ftp):\/\/[a-zA-Z0-9][\w\d&@\-#\/\%?=~_|!:,.;+]*)/i',
        function ($matches) use ($attr) {
            return '<a href="' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '"' . $attr . '>' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '</a>';
        },
        $text
    );

    // URLs starting with www.
    $text = preg_replace_callback(
        '/(?<!\/)(www\.[a-zA-Z0-9][\w\d&@\-#\/\%?=~_|!:,.;+]*)/i',
        function ($matches) use ($attr) {
            return '<a href="https://' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '"' . $attr . '>' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '</a>';
        },
        $text
    );

    // Email addresses
    $text = preg_replace_callback(
        '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i',
        function ($matches) use ($attr) {
            return '<a href="mailto:' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '"' . $attr . '>' . htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8') . '</a>';
        },
        $text
    );

    return $text;
}

Usage:

PHP
<?php
// Usage example
$text = "Visit https://example.com or www.test.com. Contact me at test@example.com.";
$link_attributes = [
	"class" => "external-link",
	"target" => "_blank"
];
$result = convert_url($text, $link_attributes);
echo $result;