views:

180

answers:

3

I've recently been working with a simple Twitter API for PHP and came across this code to make @username be linked with twitter.com/username. Unfortunately this code creates it so @username links to http://twitter.com/@username, resulting in error. There are many parts to this code I do not understand, such as ^\v and others (seen below). Can anyone give me an explanation of what they signify?

$ret = preg_replace('/(^|[^\w])(@[\d\w\-]+)/', '\\1<a href="http://twitter.com/$2"&gt;$2&lt;/a&gt;' ,$ret);
+2  A: 

Easy one:

$ret = preg_replace('/(^|[^\w])@([\d\w\-]+)/', '\\1<a href="http://twitter.com/$2"&gt;@$2&lt;/a&gt;' ,$ret);

The only difference is the @ was moved out of the capturing group, which means it has to be manually added to the output within the link.

Also, \w includes digits so the \d is superfluous. So you could simply it to:

$ret = preg_replace('/^|([^\w])@([\w\-]+)/', '\\1<a href="http://twitter.com/$2"&gt;@$2&lt;/a&gt;' ,$ret);
cletus
+1  A: 

to remove the @, use:

$ret = preg_replace('/(^|[^\w])@([\d\w\-]+)/', '\\1<a href="http://twitter.com/$2"&gt;$2&lt;/a&gt;' ,$ret);

This moves the @ outside the of the second capture group

Also see http://www.regular-expressions.info/ for some excellent information on regular expressions (in multiple languages)

Jonathan Fingland
+1  A: 

Well, to answer your question, ^\v means the first character must be a "vertical space" character. Basically it means that "starts with a blank new line"

EDIT: Looks like you actually meants the much more common ^\w which means "must start with a 'word' character." That is, a letter or a number.

You can find out what all these characters signify here

Eli