views:

43

answers:

1

I want to search the text property of my twitter status objects and swap out @username for <a href="http:/twitter.com/username">@username</a>. What I have tried so far looks like this:

$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/';
$replace = '<a href="http://twitter.com/\2"&gt;\1\2&lt;/a&gt;';
$new_string = preg_replace($pattern, $replace, $text);

But it doesn't do any replacements. I know my reg exp is wrong but I can't figure out exactly where/why. Help?

**Edit: ... sample data as requested?

$text = '@janesmith I like that, but my friend @johndoe said it better.';

Desired output:

@janesmith I like that, but my friend @johndoe said it better.

***** MY FULL FUNCTION *****

function linkify($string, $twitter=false) {

    // reg exp pattern
    $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

    // convert string URLs to active links
    $new_string = preg_replace($pattern, "<a href=\"\\0\">\\0</a>", $string);

    if ($twitter) {
        $pattern = '/@([a-zA-Z0-9_]+)/';
        $replace = '<a href="http://twitter.com/\1"&gt;@\1&lt;/a&gt;';
        $new_string = preg_replace($pattern, $replace, $new_string);
    }

    return $new_string;
}
+2  A: 

Why is the \ there before _? Does it work if you take out the \? Though that shouldn't have broken the functionality...

It might be helpful to change the \1 to \\1 so that you're sure the backslash is escaped; or better (since PHP 4.0.4) $1. But again, it should have worked as-is, within single quotes.

Also, you can simplify:

$pattern = '/@([a-zA-Z0-9_]+)/';
$replace = '<a href="http://twitter.com/$1"&gt;@$1&lt;/a&gt;';
LarsH
Good points -- I added the extra business around the @ when it wasn't working in case that was the problem. I just simplified as you suggest and removed the `\ ` before the `_` but it still doesn't replace.
Jason Rhodes
@Jason, what happens if you use `$1` instead of `\1`?
LarsH
@Jason, I tried the above at http://www.regular-expressions.info/javascriptexample.html and it worked fine. So I'm kind of at a loss as to what else could be wrong.
LarsH
Your fix ended up working, so long as I remembered to pass TRUE as the second argument of my linkify() function call. *smacks head*
Jason Rhodes
@Jason: Ah! :-p
LarsH