我正在尝试制作 Whatsapp 风格的文本帖子。当用户创建这样的文本时:
*Hi* ~how are you~ _where are you?_
然后这个文本会像这样自动改变
Hi你好吗你在哪
我知道我可以使用 php 正则表达式来做到这一点,如下所示:
该示例适用于粗体文本:
function makeBoldText($orimessage){
$message = $orimessage;
$regex = "/\*([\w]*)\*/";
$message = preg_replace($regex, '<strong>$0</strong>', $message);
return $message ;
}
echo makeBoldText($message);
但有一个问题应该删除*
当输出文本时。
其他正则表达式也应该是这样的:
Bold:
/\*([\w]*)\*/
Italic:
/_([\w]*)_/
删除线:
/~([\w]*)~/
我的问题是,我可以在一个正则表达式中完成所有这一切吗?输出时可以删除特殊字符吗?
您可以使用一次调用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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)