将聊天文本中的成对符号替换为 html 标签,以设置粗体、斜体和删除线样式

Azz*_*zzo 3 html php regex parsing preg-replace

我正在尝试制作 Whatsapp 风格的文本帖子。当用户创建这样的文本时:

*Hi* ~how are you~ _where are you?_
Run Code Online (Sandbox Code Playgroud)

然后这个文本会像这样自动改变

嗨,你好吗,你在哪里

我知道我可以使用 php 正则表达式来做到这一点,如下所示:

该示例适用于粗体文本:

function makeBoldText($orimessage){
    $message = $orimessage;
    $regex = "/\*([\w]*)\*/";
    $message = preg_replace($regex, '<strong>$0</strong>', $message);
    return  $message ;
}
echo makeBoldText($message);
Run Code Online (Sandbox Code Playgroud)

但有一个问题,*当输出文本时应该将其删除。

其他正则表达式也应该是这样的:

大胆的:

/\*([\w]*)\*/ 
Run Code Online (Sandbox Code Playgroud)

斜体:

/_([\w]*)_/ 
Run Code Online (Sandbox Code Playgroud)

删除线:

 /~([\w]*)~/
Run Code Online (Sandbox Code Playgroud)

我的问题是,我可以在一个正则表达式中完成所有这一切吗?输出时可以删除特殊字符吗?

anu*_*ava 6

您可以在此处使用一次调用preg_replace_callback

$styles = array ( '*' => 'strong', '_' => 'i', '~' => 'strike');

function makeBoldText($orimessage) {
   global $styles;
   return preg_replace_callback('/(?<!\w)([*~_])(.+?)\1(?!\w)/',
      function($m) use($styles) { 
         return '<'. $styles[$m[1]]. '>'. $m[2]. '</'. $styles[$m[1]]. '>';
      },
      $orimessage);
}

// call it as:
$s = '*Hi* ~how are you~ _where are you?_';
echo makeBoldText($s);
//=> <strong>Hi</strong> <strike>how are you</strike> <i>where are you?</i>
Run Code Online (Sandbox Code Playgroud)