开发者

How do I make a URL text a link?

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开发者_如何学Go 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?


<?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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜