0

I'm trying to convert something like this:

@Username

into:

<a href="Username">Username</a>

Can't find a RegEx for it anywhere though. Any suggestions?

Thanks!

2
  • Beware of input like <img alt="@username"> -- you don't want to insert a <a> tag inside another tag's attribute value. As a result, your best bet is actually to construct a proper dom tree. Commented Dec 6, 2012 at 22:31
  • 1
    Can't find a RegEx for it anywhere Try first, you're not going to find all regex on the internet, it's worth learning. You can start here regular-expressions.info. Commented Dec 6, 2012 at 22:35

2 Answers 2

5

You can use the preg_replace function for this:

$str = preg_replace('/@(\w+)/', '<a href="$1">$1</a>', $str);

I would also recommend you read the documentation on regular expressions.

Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$str = "Sample text @Username sample text.";
$new_str = preg_replace( '\@([a-zA-Z0-9]*)', '<a href="$1">$1</a>', $str );

echo $new_str;
?>

I think that's gonna work.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.