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