1

I have combined MathJax and Markdown markup and therefore I need to replace all $$ with <span>$$</span> so that Markdown don't render $$_^... signs from MathJax. Also all \[ \] must be replaced with <div>\[ \]</div>.

I found similar question but it's not exactly what I need. I need to convert this

This is $some$ math \[equation\] which I $like$.

to this

This is <span>$some$</span> math <div>\[equation\]</div> which I <span>$like$</span>.

Probably what I need to to is just in regex

text = text.replace(/\$.*?\$/g, "meow");

somehow include and $$ signs (or \[ \]) and just with $1 embed the text inside <span>$$1$</span> and adapt to PHP.

Community
  • 1
  • 1
svenkapudija
  • 5,128
  • 14
  • 68
  • 96

1 Answers1

1

You need to do it in two steps because the replacement texts are different.

First, replace the $..$:

$text = preg_replace('/\$.*?\$/', '<span>\0</span>', $text);

Then, replace the \[...\]:

$text = preg_replace('/\\\\\[.*?\\\\\]/', '<div>\0</div>', $text);
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • The second one also caches double backslash as a replacement and from `Test \\ Blah` I get `Test
    \\
    Blah`. Also I'm using PHP equivalents `/(\$.*?\$)/, "$1"` and `/(\\\[.*?\\\])/, "
    $1
    "`.
    – svenkapudija Jun 25 '12 at 09:34
  • @svenkapudija: I'm not following. You're using those in JavaScript, right? The second one shouldn't be capturing "\\" because the `\[` is mandatory. – Tim Pietzcker Jun 25 '12 at 09:37
  • PHP actually, my fault, now I added the tag to the question. I removed the javascript escapes and it doesn't mark double backslash but neither the `\[ \]` signs - `/(\[.*?\])/` – svenkapudija Jun 25 '12 at 09:46
  • @svenkapudija: OK, in that case you need to change the regex because PHP needs four backslashes in a regex to match a single literal backslash. (And use `\0` instead of `$&`.) See my edit. – Tim Pietzcker Jun 25 '12 at 09:53
  • Got it! Also needed `/s` modifier at the end for multiple lines (overlooked that one). Thanks. – svenkapudija Jun 25 '12 at 09:57
  • I need one additional requirement, it should do this replacement but only if the character before $ is not `\\` (backslash). So $test$ should be replaced but not \$test\$. – svenkapudija Jul 08 '12 at 13:05
  • @svenkapudija: I suspect the problem is more complicated - you need to check for an odd number of backslashes. – Tim Pietzcker Jul 08 '12 at 13:16
  • Yeah, you're right, but for now this basic solution will work just fine. – svenkapudija Jul 08 '12 at 13:41