Regex to find a hashtag in a string - without taking the original hashtag character

I'm trying to do this in PHP and I'm just wondering how I'm not very good at Regex.

I am trying to find all the hashtags in a string and wrap them with a twitter link. For this I need the hashtag content without the symbol.

I want to select #hashtag

- no preceding #

=> Just to return hashtag

?

I would like to do it in one line, but I am doing preg_replace

followed by a line as shown:

$string = preg_replace('/\B#([a-z0-9_-]+)/i', '<a 
href="https://twitter.com/hashtag/$0" target="_blank">$0</a> ', $string);
    $string = str_replace('https://twitter.com/hashtag/#', 'https://twitter.com/hashtag/', $string);

      

Any guidance would be appreciated!

+3


source to share


1 answer


I used the regex tester and found the answer.

preg_replace

returned two values: one $0

with a value #hashtag

and one $1

with a value hashtag

without the # character.

Tested here (select preg_replace): http://www.phpliveregex.com/p/kOn

Perhaps it has something to do with the regex itself, I'm not sure. Hope this helps someone else too.



My one liner:

$string = preg_replace('/\B#([a-z0-9_-]+)/i', '<a href="https://twitter.com/hashtag/$1" target="_blank">$0</a> ', $string);

      

Edit: I understand this now. The added parentheses ( )

around the square brackets effectively return the variable $1

. Otherwise the whole pattern $0

.

+6


source







All Articles