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 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示