tags:

views:

84

answers:

2

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?

+6  A: 
<?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"&gt;http://myyn.org&lt;/a&gt; dolor sit amet, \
<a href="http://google.com"&gt;http://google.com&lt;/a&gt; adipisicing elit.
The MYYN
thank you. I'm new to regular expressions so it'll take some time to digest this.
jpjp
+2  A: 

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"&gt;\\1&lt;/a&gt;', $str);
echo $str; // @<a href="http://twitter.com/obama"&gt;obama&lt;/a&gt; this is a test
Piro
thank you! works perfectly. Now I'm trying to understand it. What exactly is the \1 and \2?
jpjp
The text matched between the brackets "`(` and `)`" can be referenced back by using \\\[number], the first brackets will be in \\1, the second on \\2 and so on. See also http://www.regular-expressions.info/brackets.html.A good read on my word character shorthand (`\w`) can be found at http://www.regular-expressions.info/charclass.html.
Piro
ahh I see, that got me. i'll look into the books.
jpjp