phpregexhyperlinktext-parsinghashtag

Convert hashtags to hyperlinks


I'm looking for a regex that will recognize # followed by a number in a string and make it clickable. Only if its # and a number like ex: #758 and make I clickable. Not # 758. Youtube has this for example.


Solution

  • Try this:

    preg_replace('/#\\d+/', '<a href="$0">$0</a>', $str);
    

    The regex is basically /#\d+/, so the # character followed by one or more digits. preg_replace is to replace such occurences with <a href="$0">$0</a> where $0 is replaced by the match that has been found.

    And if you just need the number, use /#(\d+)/ and <a href="$1">$1</a> instead.