Page 1 of 1

Match on dollar sign. HELP

Posted: Thu May 13, 2010 4:04 pm
by KawasakiMike9
I'm looking to make a regex that gets a word that starts with a dollar sign and am having some trouble. Ex:

String : "Hello world. My name is $Michael";

I want the preg_replace to replace it with:

http://www.twitter.com/Michael/

Here is what I've tried

"\$([A-Za-z]\s)#ise", "'\\1<a href=\"http://www.twitter.com/\\1\" >\\1</a>'"

but something seems to be wrong or I'm going about this the wrong way. Could someone offer some advice on this?

Thanks

Re: Match on dollar sign. HELP

Posted: Thu May 13, 2010 4:28 pm
by AbraCadaver
Couple of problems:

1. You have no starting delimiter #
2. Your pattern is looking for one $ followed by one letter followed by one whitespace character
3. You don't need any of those modifiers
4. Assuming you're using PHP, since its in double quotes, $Michael is interpolated as a variable and replaced with the contents of the $Michael variable, or nothing if it doesn't exist
5. A single escaped $ won't work in double quotes in the pattern (at least in PHP)

This works:
[text]'#\$([A-Za-z]+)#'[/text]
Or this:
[text]"#\\$([A-Za-z]+)#"[/text]

Re: Match on dollar sign. HELP

Posted: Sun May 16, 2010 12:36 pm
by ridgerunner
Here's how I would do it:

Code: Select all

$str = preg_replace('/\$(\w++)/', '<a href="http://www.twitter.com/$1/">$1</a>', $str);
:)