PHP bbcode功能提到用户

问题描述 投票:0回答:1

我有一个在论坛帖子上使用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在使用时变为粗体。有没有办法做到这一点?

php regex
1个回答
4
投票

您似乎已经尝试使用最后一个正则表达式执行此操作。试试这个你的正则表达式:

'/(@\w+)/'

并在替换字符串中将$4更改为$1

© www.soinside.com 2019 - 2024. All rights reserved.