URLs in Text finden, Links erstellen

Avatar of Chris Coyier
Chris Coyier am
<?php

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

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

// 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;

}
?>

Die grundlegende Funktion besteht darin, URLs im Textblock zu finden und sie in Hyperlinks umzuwandeln. Es werden nur korrekt formatierte URLs gefunden, d. h. sie müssen http, https, ftp oder ftps enthalten.

Schauen Sie sich die Kommentare unten für weitere Lösungen an.