我有一个在论坛帖子上使用preg_replace的PHP代码。我希望我的用户能够提及他们的朋友,例如@john @jane
我使用以下功能将BBcode转换为HTML。
function bbc2html($content) {
$search = array (
'/(\[b\])(.*?)(\[\/b\])/',
'/(\[B\])(.*?)(\[\/B\])/',
'/(\[i\])(.*?)(\[\/i\])/',
'/(\[I\])(.*?)(\[\/I\])/',
'/(\[u\])(.*?)(\[\/u\])/',
'/(\[U\])(.*?)(\[\/U\])/',
'/(\[ul\])(.*?)(\[\/ul\])/',
'/(\[li\])(.*?)(\[\/li\])/',
'/(\[url=)(.*?)(\])(.*?)(\[\/url\])/',
'/(\[url\])(.*?)(\[\/url\])/',
'/(\[size=)(.*?)(\])(.*?)(\[\/size\])/',
'/(\[img\])(.*?)(\[\/img\])/',
'/(\[IMG\])(.*?)(\[\/IMG\])/',
'/(\[strike\])(.*?)(\[\/strike\])/',
'/(\[STRIKE\])(.*?)(\[\/STRIKE\])/',
'/(\[youtube\])(.*?)(\[\/youtube\])/',
'/(\[YOUTUBE\])(.*?)(\[\/YOUTUBE\])/',
'/(\[left\])(.*?)(\[\/left\])/',
'/(\[LEFT\])(.*?)(\[\/LEFT\])/',
'/(\[CENTER\])(.*?)(\[\/CENTER\])/',
'/(\[center\])(.*?)(\[\/center\])/',
'/(\[RIGHT\])(.*?)(\[\/RIGHT\])/',
'/(\[right\])(.*?)(\[\/right\])/',
'/(\[JUSTIFY\])(.*?)(\[\/JUSTIFY\])/',
'/(\[justify\])(.*?)(\[\/justify\])/',
'/(\[color=)(.*?)(\])(.*?)(\[\/color\])/',
'/(\[COLOR=)(.*?)(\])(.*?)(\[\/COLOR\])/',
'/(\@)(.*?)/'
);
$replace = array (
'<span style="font-weight: 700;">$2</span>',
'<span style="font-weight: 700;">$2</span>',
'<em>$2</em>',
'<em>$2</em>',
'<u>$2</u>',
'<u>$2</u>',
'<ul>$2</ul>',
'<li>$2</li>',
'<a href="$2" target="_blank">$4</a>',
'<a href="$2" target="_blank">$4</a>',
'<span style="font-size: $2;">$4</span>',
'<img src="$2" style="max-width: 100%;">',
'<img src="$2" style="max-width: 100%;">',
'<strike>$2</strike>',
'<strike>$2</strike>',
'<iframe width="500" height="315" src="http://www.youtube.com/embed/$2?modestbranding=1" frameborder="0"></iframe>',
'<iframe width="500" height="315" src="http://www.youtube.com/embed/$2?modestbranding=1" frameborder="0"></iframe>',
'<span class="left">$2</span>',
'<span class="left">$2</span>',
'<center$2</center>',
'<center>$2</center>',
'<span class="right">$2</span>',
'<span class="right">$2</span>',
'<span class="justify">$2</span>',
'<span class="justify">$2</span>',
'<span style="color: $2">$4</span>',
'<span style="color: $2">$4</span>',
'<span style="font-weight: 700;">$4</span>'
);
return preg_replace($search, $replace, $content);
}
我希望@username在使用时变为粗体。有没有办法做到这一点?
答案 0 :(得分:4)
看起来您已经尝试使用最后一个正则表达式执行此操作。试试这个你的正则表达式:
'/(@\w+)/'
并将替换字符串中的$4
更改为$1