用 html 标签替换聊天文本中的符号对,使其样式为粗体、斜体和删除线 [英] Replace pairs of symbols in chat text with html tags to style as bold, italic, and strikethrough

查看:58
本文介绍了用 html 标签替换聊天文本中的符号对,使其样式为粗体、斜体和删除线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 whatsapp 风格的文本帖子.当用户创建这样的文本时:

I am trying to make a whatsapp style text post. When user create text like this:

*Hi* ~how are you~ _where are you?_

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

then this text is automatically changing like this

你好吗你在哪里

我知道我可以像这样使用 php regex 来做到这一点:

I know i can do it with php regex like this:

该示例适用于粗体文本:

The example is for bold text:

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

但是有一个问题,应该在输出文本时去掉*.

But there is a problem it should be remove * when text is outputed.

另一个正则表达式也应该是这样的:

The other regex also should be like this:

粗体:

/\*([\w]*)\*/ 

斜体:

/_([\w]*)_/ 

删除线:

 /~([\w]*)~/

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

推荐答案

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

You may use a single call to preg_replace_callback here:

$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>

这篇关于用 html 标签替换聊天文本中的符号对,使其样式为粗体、斜体和删除线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆