Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hashtag text into a hashtag hyperlink?

I'm using php's preg_replace() to convert any words that have a hashtag symbol in front of them into hyperlinks.

So something like: #austin would become: <a href="/tag/austin">#austin</a>

Here is my regular expression.

preg_replace('/\B#(\w*[A-Za-z_]+\w*)/', '<a href="/tag/$1">$0</a>', $text);

My issue is: if there are any capitalized letters, the href value will retain them, but I want the href value to always be entirely lowercase.

Input: #Austin
Should not become: <a href="/tag/Austin">#Austin</a>
It should become:<a href="/tag/austin">#Austin</a>

How could I modify my regular expression to create these results?

like image 202
floatleft Avatar asked Jun 27 '11 16:06

floatleft


2 Answers

Here's an example using preg_replace_callback as suggested by @faileN:

Demo Link

$string = '#Austin';

function hashtag_to_link($matches)
{
  return '<a href="/tag/' . strtolower($matches[1]) . '">' . $matches[0] . '</a>';
}

echo preg_replace_callback('/\B#(\w*[a-z_]+\w*)/i', 'hashtag_to_link', $string);

// output: <a href="/tag/austin">#Austin</a>
like image 148
Francois Deschenes Avatar answered Oct 05 '22 15:10

Francois Deschenes


Try this:

preg_replace('/\B#(\w*[A-Za-z_]+\w*)/', '<a href="/tag/$1">$0</a>', strtolower($text));

That will force the subject ($text) to be in lowercase before the regex is tested.

like image 21
David Laberge Avatar answered Oct 05 '22 16:10

David Laberge