1

Okay so thanks to folks on this forum I finally got a simple twitter online website working. Now I have run into another problem.

I have a twitter feed say the sample text is:

The cat will always be in the bag @folks @charliesheen

Now I had the idea of using regular expressions to find all @_ strings in the text and replace them with

<a href="index.php?".$(matched_string - @)>matched_string</a>

Any ideas on how I can possibly go about doing this?

1 Answer 1

4

Here's something I hacked up quickly. \S means "any character that's not whitespace".

$str = 'The cat will always be in the bag @folks @charliesheen';
$str = preg_replace('/@(\S*)/', '<a href="index.php?$1">$1</a>', $str);

EDIT: To be safe, you should make sure all the characters in the URL are "url-safe".

$str = 'The cat will always be in the bag @folks @charliesheen';
$str = preg_replace_callback('/@(\S*)/', function($x){
    return '<a href="index.php?'.urlencode($x[1]).'">'.$x[1].'</a>';
}, $str);
Sign up to request clarification or add additional context in comments.

9 Comments

Oh my god I love you! I was looking for that $1...couldn't find it anywhere. THANKS A LOT!
@hakre: I could also make sure the regex only matches url-safe characters too. :-P
@user1123599: Check the docs for preg_replace. :-)
@Rocket: That's fine! Always take care of the average joe here that just copies and pastes code from the site. So it's better to provide a little more safe code.
I ended up changing the regex to '/@([A-Za-z0-9_]*)/' because for twitter handles characters such as ':' are not allowed...just in case someone is interested in the future...Thanks for the encoded url function...REALLY helpful!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.