dongshu4221 2014-01-06 06:55
浏览 537
已采纳

自定义“Markdown”式标签

I want to create custom tags for different things like bold, underline and italic without using a Markdown library/class.

For example

*Bold text*
/Italic text/
_Underlined text_

So the above would be changed to:

<strong>Bold text</strong>
<em>Italic text</em>
<u>Underlined text</u>

I have no idea where to begin and have been searching for a solution for ages.

I read a few tutorials on regular expressions but still unsure how to approach this.

Thanks in advanced.

  • 写回答

1条回答 默认 最新

  • duanjie9630 2014-01-06 08:24
    关注

    Here is a recursive function to do that with regex. The tricky part (for me) was the use of forward slash / which is also used in the close tags. So at first i insert {} and replaces those with / in the very end.

    test text :

    $input ="
    *Bold text*
    bla bla bla
    /Italic text/
    bla bla bla
    _Underlined text_
    bla bla bla
    ";
    

    replace function :

    function markdown(&$text, $code, $tag, $open) {
        if (strpos($text, $code)) {
            $insertTag=($open) ? '<'.$tag.'>' : '<{}'.$tag.'>';
            $reg='['.preg_quote($code).']';
            $text=preg_replace($reg, $insertTag, $text, 1);
            markdown($text, $code, $tag, !$open);
        } else {
            return;
        }
    }
    

    run :

    markdown($input, '*', 'strong', true);
    markdown($input, '/', 'em', true);
    markdown($input, '_', 'u', true);
    $input=str_replace('{}', '/', $input);
    echo $input;
    

    outputs :

    <strong>Bold text</strong>
    bla bla bla
    <em>Italic text</em>
    bla bla bla
    <u>Underlined text</u>
    bla bla bla
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作