Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a URL text a link?

Tags:

php

Say on Facebook or Twitter, when I type "www.google.com" and submit it, it becomes a link. How do I code this in PHP? Do I use regular expressions to get where the www starts and the .com ends?

Is this how they do it?

<?PHP 
//some regular expression to get www and .com part
$link="<a href='$url'>$url</a>";
echo $link;
?>

How do I write a regular expression to get the "www" and ".com" part?

And for twitter's @obama, obama would become a link to obama's site. What regular expression do they use to get the text after the @ and before the space?

like image 745
jpjp Avatar asked Nov 26 '25 21:11

jpjp


2 Answers

<?php

$str = "Lorem http://myyn.org dolor sit amet, http://google.com adipisicing ..";

$str = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is",
                    "\\1<a href=\"\\2\">\\2</a>", 
                    $str); 

echo $str . "\n";

?>

Example:

$ php 2935574.php 
Lorem <a href="http://myyn.org">http://myyn.org</a> dolor sit amet, \
<a href="http://google.com">http://google.com</a> adipisicing elit.
like image 57
miku Avatar answered Nov 28 '25 11:11

miku


And for Twitter you could use something like this.

$str = "@obama This is a test";
$str = preg_replace('/@([\w-]+)/', '@<a href="http://twitter.com/\\1">\\1</a>', $str);
echo $str; // @<a href="http://twitter.com/obama">obama</a> this is a test
like image 20
Piro Avatar answered Nov 28 '25 10:11

Piro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!