PHP tutorial, How to detect links in the comments

You might have come across platforms like Facebook, google e.t.c detecting links in the commenting systems, today we are going to learn how to detect links in the comments or in any phrase of text using PHP.

Download Example Project

How to detect links in the comments using PHP


This code will illustrate how you should detect links in the commenting systems using PHP.

Also Read: How to validate email with PHP and how to detect if string is contained in another string in php

<?php
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";


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

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

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

} else {

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

}
?>



Also Read: How to use SQL LIKE CLAUSE in PHP using PDO



DEMO VIDEO