Today we talk about How to Find URLs in Content, Make Links For Multiple URLs. As the heading suggests we create a PHP function where that function finds the URLs on the content or paragraph or any type of string. This function find all URLs, means 2 or multiple URLs from the content.
Copy code and use Online PHP Editor for live: PHP EDITOR

Using this PHP function you can find multiple URLs from the content and make links or add <a> tag on that links. See below source,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php function makeUrlIntoAlink($string){ //The Regular Expression filter $reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/"; // Check if there is a url in the text if(preg_match_all($reg_exUrl, $string, $url)) { // Loop through all matches foreach($url[0] as $newLinks){ if(strstr( $newLinks, ":" ) === false){ $link = 'http://'.$newLinks; }else{ $link = $newLinks; } // Create Search and Replace strings $search = $newLinks; $replace = '<a href="'.$link.'" title="'.$newLinks.'" target="_blank">'.$link.'</a>'; $string = str_replace($search, $replace, $string); } } //Return result return $string; } echo makeUrlIntoAlink("simple PHP function checks if the content contains a URL (e.g. www.google.com) and then takes that URL and converts it into a link.") ?> |
Also, check:
How to Create Pagination in PHP with Ajax
Happy Coding..!
Was this article helpful?
YesNo
hi, how can I convert this code to detetc only the first lisnk
for exmaple “something blah blah http://www.google.com/somethingelse/somethingelse“.
I just want to detect the “http://www.google.com/somethingelse/somethingelse”, and avoid any other URLs after that.