How to convert hashtag text to hashtag hyperlink?

I use php preg_replace()to convert any words that have a hashtag character in front of them into hyperlinks.

So, something like: #austinbecomes:<a href="/tag/austin">#austin</a>

Here is my regex.

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

My problem: if there are uppercase letters, the href value will keep them, but I want the href value to always be completely lowercase.

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

How can I change my regex to create these results?

+5
source share
4 answers

Here is a usage example preg_replace_callbacksuggested 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>
+5

:

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

($text) .

+3

You can achieve this with preg_replace_callback: http://de2.php.net/manual/en/function.preg-replace-callback.php

+2
source

In theory, you can use a modifier ethat allows you to use PHP functions in the replacement string:

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

All Articles