This article will explore different techniques to automatically generate HTML links with PHP.

Conversions from URL to link are commonly used with user-generated content. For example, you can apply this technique to blog comments or forum areas.

We can perform this operation in two steps. First, we have to detect the URLs in the text; then, we must replace the URLs with link elements that use the considered URL both in the src attribute and in the anchor text.

The best solution to perform this kind of replacement is to use the PCRE functions provided by PHP. In particular, this example uses the preg_replace() PHP function, which allows us to find the match and apply the replacement with a single instruction.

In the example below, the convert() function replaces all the URLs available in the provided string with links.

/**
 * This functions converts the URLs available in the provided string to links.
 *
 * @param $s
 *
 * @return array|string|string[]|null
 */
function convert($s) {

	//A regular expression to find the URLs
	$url_regex = '<https?:\/\/(www\.)?[[email protected]:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)>';

	//The preg_replace() function applies the links by using the captured groups of the URL regex
	return preg_replace($url_regex, '<a href="$0" title="$0">$0</a>', $s);

}

$html = 'My website is http://example.com';

echo convert($html);

//Output: My website is <a href="http://example.com" title="http://example.com">http://example.com</a>

The PHP Autolink library is available on GitHub, and you can install it in a few seconds in your PHP environment with Composer.

With this library, you can convert URLs or email addresses to links with the two provided methods, convert() and convertEmail().

The example below uses this library to convert all the URLs included in the $html string to links.

//Load the library with composer
require_once( 'vendor/autoload.php' );
use Asika\Autolink\Linker;

//Convert the URL in this string to a link
$html = 'My website is https://example.com';
echo Linker::convert($html);

//Output: My website is <a href="https://example.com">https://example.com</a>

It’s sometimes convenient to convert the email addresses included on a page to links that open the email client. Let’s explore two implementation methods.

In this custom implementation, I use a regular expression provided by this specialized website to find all the emails in the string. Note that this time the value of the href attribute is composed by the prefix mailto: followed by the email address.

/**
 * This function converts the email addresses available in the provided string to URLs.
 *
 * @param $s
 *
 * @return array
 */
function email_to_link($s) {

	//A regular expression that matches the email addresses
	$email_regex = '/([A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,})/i';

	//A link with the "mailto:" prefix
	return preg_replace($email_regex, '<a href="mailto:$0" title="$0">$0</a>', $s);

}

$html = 'My email address is [email protected]';

echo email_to_link($html);

//Output: My email address is <a href="mailto:[email protected]" title="[email protected]">[email protected]</a>

This example uses the PHP Autolinks library again, but this time with convertEmail(). This method converts all the emails in the string to links.

//Load the library with composer
require_once( 'vendor/autoload.php' );
use Asika\Autolink\Linker;

//Convert the emails in this string to links
$html = 'My email address is [email protected]';
echo Linker::convertEmail($html);

//The above example will output
//Output: My email address is <a href="mailto:[email protected]">[email protected]</a>

This section aims to illustrate methods to automatically replace specific keywords to link.

In the real world, automatic links generated on a list of defined keywords are commonly used to increase the number of internal links, create affiliate links, or link specific glossary terms to their definitions.

Replace the keywords with a custom solution

We can complete this process in three steps:

  1. Create a list of keywords with the related URLs
  2. Iterate the list of keywords
  3. Replace the keywords with links

Create an array that includes the keywords and the related URLs.

//The keywords with the related URLs
$data_a = [
	[
		'keyword' => 'book',
		'url' => 'https://example.com/book/'
	],
	[
		'keyword' => 'amazon',
		'url' => 'https://example.com/amazon/'
	]
];

Then write a function that converts the single keywords to links:

/**
 * This functions converts keywords to links.
 *
 * @param $s
 *
 * @return array|string|string[]|null
 */
function convert($html, $data) {

	$regex = '/(' . $data['keyword'] . ')/i';

	return preg_replace($regex, '<a href="' . $data['url'] . '">$0</a>', $html);

}

Now you can iterate over the keyword data to automatically apply the links.

$html = 'My book is published on Amazon.';

//Iterate over the keyword data
foreach($data_a as $data){

	//Convert this specific keyword to a link
	$html = convert($html, $data);

}

//Echo the resulting HTML
echo $html;

In the resulting output, the keywords in the string have been replaced with links:

My <a href="https://example.com/book/">book</a> is published on <a href="https://example.com/amazon/">Amazon</a>.

Automatic Links is a PHP class from our portfolio that we initially developed to implement the automatic links functionalities of the Interlinks Manager WordPress plugin.

The main advantage of using this library is that you have many customization options to control the replacements of the keywords. For example, you can limit the number of automatic links, protect specific HTML tags, prevent multiple links to the same destination, etc.

The example below uses this class to replace all the occurrences of the keyword “iPhone” with links.

//Include the "Automatic Links" library in the PHP script
require_once( 'inc/class-daext-automatic-links.php' );
$automatic_links = new DaextAutomaticLinks();

//Add the link data. In this case only one autolink for the keyword "iPhone" has been added
$data = [
	[
		'keyword' => "iPhone",
		'url'     => "https://example.com/iphone/"
	]
];

//Add the links to the string and echo the result
echo $automatic_links->add_autolinks( 'The new iPhone', $data );

//Output: The new <a href="https://example.com/iphone/">iPhone</a>