Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

regex - Convert plain text URLs into HTML hyperlinks in PHP

I have a simple commenting system where people can submit hyperlinks inside the plain text field. When I display these records back from the database and into the web page, what RegExp in PHP can I use to convert these links into HTML-type anchor links?

I don't want the algorithm to do this with any other kind of link, just http and https.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an other solution, This will catch all http/https/www and convert to clickable links.

$url = '~(?:(https?)://([^s<]+)|(www.[^s<]+?.[^s<]+))(?<![.,:])~i'; 
$string = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

Alternatively for just catching http/https then use the code below.

$url = '/(http|https|ftp|ftps)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/S*)?/';   
$string= preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

EDIT: The script below will catch all url types and convert them to clickable links.

$url = '@(http)?(s)?(://)?(([a-zA-Z])([-w]+.)+([^s.]+[^s]*)+[^,.s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

New update, If you're having the string strip the (s) then use the below code block, Thanks to @AndrewEllis for pointing this out.

$url = '@(http(s)?)?(://)?(([a-zA-Z])([-w]+.)+([^s.]+[^s]*)+[^,.s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

Here's a very simple solution for the URL not displaying correctly.

$email = '<a href="mailto:[email protected]">[email protected]</a>';
$string = $email;
echo $string;

It is a very simple fix but you will have to modify it for your own purpose.

I've provided multiple answers as some servers are setup differently, so one answer may work for some but not for others, but I hope the answer(s) work for you and if not then let me know and hopefully I can come up with another solution.

There are multiple scripts as some PHP files require different scripts also some servers are setup differently, Plus each have different requirements, Some want just HTTP/S, some want WWW and some want FTP/S, Each one will work depending on how the users own scripts are setup, I provided some text with each one with what they do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...