简体   繁体   English

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

[英]Regex to replace similar delimiters of strings

I have checked out various Regex answers here on StackOverflow but I can't find anything related to my problem. 我已经在StackOverflow上检查了各种Regex答案,但是找不到与我的问题相关的任何内容。

I have some webpage text (LaTeX actually) of forms $inline_latex$ and $$paragraph_latex$$ and I want to replace them respectively, using PHP with 我有一些网页文本(实际上是LaTeX),格式$inline_latex$$$paragraph_latex$$ ,我想分别使用PHP替换它们

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

and

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

ie replace the delimiters for $ with span tag, and for $$ with paragraph tag. 例如,将$的分隔符替换为span标记,将$$的分隔符替换为段落标记。 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. 我尝试过的事情:我在使用正则表达式时遇到了麻烦,因此我使用了str_replace 3次。 First one replaces $$ with ~ , second one replaces $ with span , third one replaces ~ with p tag. 第一个将$$替换为~ ,第二个将$替换$ span ,第三个将p替换为~ This is shoddy but it still doesn't work because I don't have a solution for the close tags. 这很伪劣,但仍然无法正常工作,因为我没有close标签的解决方案。 I know using regex / preg_replace is better. 我知道使用regex / preg_replace更好。

Please help? 请帮忙? This is not homework . 这不是功课 I am a math instructor designing a simple class exercise webpage, and I am learning PHP. 我是一位数学老师,正在设计一个简单的课堂练习网页,并且正在学习PHP。 Thanks 谢谢

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 参见演示12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM