开发者

How to convert hashtag text into a hashtag hyperlink?

I'm using php's preg_replace() t开发者_开发技巧o 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.


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜