dopmgo4707 2017-03-04 23:59
浏览 41
已采纳

正则表达式替换类似的字符串分隔符

I have checked out various Regex answers here on StackOverflow but I can't find anything related to my problem.

I have some webpage text (LaTeX actually) of forms $inline_latex$ and $$paragraph_latex$$ and I want to replace them respectively, using PHP with

<span class="latex">\color{red}inline_latex</span>

and

<p class="latex">\color{red}paragraph_latex</p>

i.e. replace the delimiters for $ with span tag, and for $$ with paragraph tag. Multiple strings will be replaced at once, wherever $ and $$ exist.

What I have tried: I was having a hard time with regex so I used str_replace three times. First one replaces $$ with ~, second one replaces $ with span, third one replaces ~ with p tag. This is shoddy but it still doesn't work because I don't have a solution for the close tags. I know using regex / preg_replace is better.

Please help? This is not homework. I am a math instructor designing a simple class exercise webpage, and I am learning PHP. Thanks

  • 写回答

1条回答 默认 最新

  • douou1891 2017-03-05 00:08
    关注

    First replace

    \$\$([^$]+)\$\$
    

    with

    <p class="latex">\\color{red}\1</p>
    

    Then replace

    \$([^$]+)\$
    

    with

    <span class="latex">\\color{red}\1</span>
    

    See demos 1 and 2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题