You can use preg_replace_callback () like this:
$text = preg_replace_callback ("/@(\\w+)/", function ($matches) {
return '<a href="http://'. str_replace('_', '-', $matches[1]) .'.abc.com.">'.$matches[1].'</a> '; }, "test @user_john here");
質問
I have some string with hashtags looks like @user_name. Now i convert all hashtags to links this way:
$text = preg_replace ("/@(\\w+)/", '<a href="http://$1.'.SITE_NAME.'">@$1</a> ', $text);
As you can see, all hashtags becomes to subdomain names. If you know, there some problems with _
symbol in subdomain names (some browsers not supports that, IE supports, but not set cookies, etc..). So i need to replace the _
symbols in subdomain to -
(minus), but keep _
symbols in hashtag view. There link what i need to <a href="http://user-name.site.com">@user_name</a>
. How?
解決
You can use preg_replace_callback () like this:
$text = preg_replace_callback ("/@(\\w+)/", function ($matches) {
return '<a href="http://'. str_replace('_', '-', $matches[1]) .'.abc.com.">'.$matches[1].'</a> '; }, "test @user_john here");
他のヒント
Well, it looks like you already have an answer...
I was going to suggest this regex to use:
(https?:..[^\.]*)(_)([^\.]*)