简体   繁体   中英

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.

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>

ie 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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