Php to replace @username with link to twitter account

后端 未结 2 1923
慢半拍i
慢半拍i 2020-12-15 12:02

I assume this is some to do with regex, but it\'s an art all it\'s own - and I need some help.

When we display a story, we store all the text in a varilable - let\'s

相关标签:
2条回答
  • 2020-12-15 12:15

    A positive lookbehind could do the trick:

    preg_replace('/(?<=\s)@(.*?)/', '<a href="....com/$1">@$1</a>')
    

    going off the top of my head. "If there's a @ which is preceded by something which is whitespace, then take whatever follows after the @ and do the html tag wrapping".

    0 讨论(0)
  • 2020-12-15 12:32
    $input = preg_replace('/(^|\s)@([a-z0-9_]+)/i',
                          '$1<a href="http://www.twitter.com/$2">@$2</a>',
                           $input);
    

    See it

    It matches a @ which is preceded by whitespace or nothing ( when it is at the beginning).

    It can also be shorted using positive lookbehind as:

    $input = preg_replace('/(?<=^|\s)@([a-z0-9_]+)/i',
                          '<a href="http://www.twitter.com/$1">@$1</a>',
                          $input);
    

    Which matches only the twitter name but only if there is space or nothing before that.

    0 讨论(0)
提交回复
热议问题