floatleft
floatleft

Reputation: 6541

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?

Upvotes: 5

Views: 4384

Answers (4)

David Laberge
David Laberge

Reputation: 16041

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.

Upvotes: 4

Francois Deschenes
Francois Deschenes

Reputation: 24969

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>

Upvotes: 5

Karolis
Karolis

Reputation: 9562

In theory you can use e modifier which lets you use PHP functions in the replacement string:

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

Upvotes: 1

Fidi
Fidi

Reputation: 5834

You can achieve that with preg_replace_callback: https://www.php.net/manual/en/function.preg-replace-callback.php

Upvotes: 2

Related Questions