Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find hashtag in string - without taking the initial hashtag symbol

Tags:

regex

php

I'm trying to do this in PHP and I am just wondering as I'm not great with Regex.

I'm trying to find all hashtags in a string, and wrap them in a link to twitter. In order to do this I need the content of the hashtag, without the symbol.

I want to select the #hashtag - without the preceding # => Just to return hashtag?

I'd like to do it in one line but I'm doing a preg_replace, followed by a string replace 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 is apprecaited!

like image 902
shanehoban Avatar asked Jan 30 '23 22:01

shanehoban


1 Answers

I was using a regex tester and found the answer.

preg_replace was returning two values, one $0 with the #hashtag value, and $1 with the hashtag value - without the # symbol.

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

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

My one liner is:

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

Edit: I understand it now. The added brackets ( ) around the square brackets effectively return the $1 variable. Otherwise the whole pattern is $0.

like image 146
shanehoban Avatar answered Feb 03 '23 08:02

shanehoban