dorbmd1177
dorbmd1177
采纳率100%
2018-09-02 16:16

如何使用正则表达式将tex标签转换为php或sed中的html标签? [关闭]

已采纳

I have this tex:

hello \o{test} how are you?

I want to convert it into:

hello <span>test</span> how are you?

how?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dqqs64238 dqqs64238 3年前

    You may use the following expression:

    \\o\{([^}]+)}
    
    • \\o Matches o.
    • \{ Matches {.
    • ([^}]+) Capturing group. Matches and captures anything other than a }.
    • } Matches a }.

    Replacing with:

    <span>\1<\/span>
    

    Regex demo here.


    Sed implementation:

    $ echo "hello \o{test} how are you?" | sed -r 's/\\o\{([^}]+)}/<span>\1<\/span>/g'
    hello <span>test</span> how are you?
    

    Php implementation:

    <?php
    $input_lines="hello \o{test} how are you?";
    echo preg_replace("/\\\\o{([^}]+)}/", "<span>$1<\/span>", $input_lines);
    

    Prints:

    hello <span>test<\/span> how are you?
    
    点赞 评论 复制链接分享
  • duanchi4544 duanchi4544 3年前

    Without regex: using str_replace()

    <?php
    $string = 'hello \o{test} how are you?';
    echo str_replace(['\o{','}'],['<span>','</span>'],$string);
    ?>
    

    DEMO: https://3v4l.org/ttSC2

    With regex using preg_replace()

    <?php
    $re = '/\\\\o\{([^}]+)\}/m';
    $str = 'hello \\o{test} how are you?';
    $subst = '<span>$1</span>';
    echo preg_replace($re, $subst, $str);
    ?>
    

    DEMO: https://3v4l.org/FiOKO

    点赞 评论 复制链接分享