Page 1 of 1

Using regexp to replace url with hyperlink.

Posted: Wed Feb 13, 2008 6:16 am
by markusn00b
Now, i've put my hand to this and it just burns me..

How would i go about taking some user input

Code: Select all

 
$_userInput = "http://www.somesite.com is a great site!";
 
and changing it so that it was wrapped in a hyperlink

Code: Select all

 
$_userInput = "<a href=\"http://www.somesite.com\">http://www.somesite.com</a> is a great site!";
 
Any ideas?
Much appreciated.

Re: Using regexp to replace url with hyperlink.

Posted: Wed Feb 13, 2008 9:36 am
by Zoxive

Code: Select all

$Userinput = 'http://google.com';
 
$Link = "<a href=\"{$Userinput}\">{$Userinput}</a>";
 
$Link2 = '<a href="' . $Userinput . '">' . $Userinput . '</a>';
Unless you are talking about looking for all URLs and making them links.

Re: Using regexp to replace url with hyperlink.

Posted: Wed Feb 13, 2008 10:04 am
by Jonah Bron
I think that's what he means.

Code: Select all

<?php
$user_input = 'http://www.example.com was a great site!';
$site = strstr($user_input, ' ');
$comment = strstr($user_input, ' ', true);
$output = '<a href="'. $site .'">'. $comment .'</a>';
?>

Re: Using regexp to replace url with hyperlink.

Posted: Wed Feb 13, 2008 10:11 am
by Jonah Bron
Oh! I see. Sorry, ignore the last post.

Code: Select all

<?php
$user_input = 'hi.  I really liked http://www.example.com, and http://example.com !';
 
$user_input = preg_replace('/[a-z0-9-_]*?.((com)|(net))/i', "<a href=\"http://$1\">$1</a>", $user_input);
?>
Untested.

Re: Using regexp to replace url with hyperlink.

Posted: Wed Feb 13, 2008 10:48 am
by Zoxive

Code: Select all

<?php
 function replaceurl($Matches){
   $Url = $Matches[0];
   if(strstr($Url,'http://')===false){
     $Url = 'http://' . $Url;  
   } 
   return "<a href=\"{$Url}\">$Url</a>";
 }        
   
 $Regex = '((http://)|(www\.))[a-z0-9-_\.]+';
 
 $Input = 'hi there i like www.google.com and use http://gmail.com alot, http://www.google.com';
 
 $Input = preg_replace_callback("#{$Regex}#im",'replaceurl',$Input);
 
 

Code: Select all

string(193) "hi there i like <a href="http://www.google.com">http://www.google.com</a> and use <a href="http://gmail.com">http://gmail.com</a> alot, <a href="http://www.google.com">http://www.google.com</a>"

No where near prefect, but it works.