Azz*_*zzo 3 html php regex parsing preg-replace
我正在尝试制作 Whatsapp 风格的文本帖子。当用户创建这样的文本时:
*Hi* ~how are you~ _where are you?_
然后这个文本会像这样自动改变
嗨,你好吗,你在哪里
我知道我可以使用 php 正则表达式来做到这一点,如下所示:
该示例适用于粗体文本:
function makeBoldText($orimessage){
    $message = $orimessage;
    $regex = "/\*([\w]*)\*/";
    $message = preg_replace($regex, '<strong>$0</strong>', $message);
    return  $message ;
}
echo makeBoldText($message);
但有一个问题,*当输出文本时应该将其删除。
其他正则表达式也应该是这样的:
大胆的:
/\*([\w]*)\*/ 
斜体:
/_([\w]*)_/ 
删除线:
 /~([\w]*)~/
我的问题是,我可以在一个正则表达式中完成所有这一切吗?输出时可以删除特殊字符吗?
您可以在此处使用一次调用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>
| 归档时间: | 
 | 
| 查看次数: | 3182 次 | 
| 最近记录: |