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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With