Converting Plain Text Links to Clickable with RegEx


Posted on May 7, 2020


First create a file, convertTextToLink.php then add the following code:

function convertTextToLink( $text ) {
  $text = html_entity_decode( $text );
  $text = " " . $text;
  $text = preg_replace( '/(((f|ht){1}tp:\/\/)[[email protected]:%_\+.~#?&\/\/=]+)/i', '<a href="${1}" target="_blank">${1}</a>', $text );
  $text = preg_replace( '/(((f|ht){1}tps:\/\/)[[email protected]:%_\+.~#?&\/\/=]+)/i', '<a href="${1}" target="_blank">${1}</a>', $text );
  $text = preg_replace( '/([[:space:]()[{}])(www.[[email protected]:%_\+.~#?&\/\/=]+)/i', '${1}<a href="http://${2}" target="_blank">${2}</a>', $text );
  $text = preg_replace( '/([_\.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i', '<a href="mailto:${1}">${1}</a>', $text );
  return $text;
}

Then on your index.php page:

<?php
// Link the file with the function
require_once('convertTextToLink.php');

// Your choice of text
$text = "Welcome to Viper's Web Design, https://www.viperswebdesign.com/";

// Print the text to see the magic
echo convertTextToLink($text); // Output - Welcome to Viper's Web Design, <a href="https://www.viperswebdesign.com/" target="_blank">https://www.viperswebdesign.com/</a>
?>

Recent Posts


Categories

  • Entertainment
    • Viewing Orders
  • Tutorials
    • PHP