Replace $ x <y $ with $ x <y $
I want to search the text for a smaller sign <between dollar signs, for example $x<y$, and replace it with $x < y$.
I use mathjax and less than a character, causes some problems when rendering Mathjax. (See here: http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents ).
I tried
$text = preg_replace("/\$(.*?)(<)(.*?)\$/","/\$$1 < $3\$/",$text), but I'm not sure if this is a good solution. I am new to programming :)
Thank you for your help.
+4
3 answers
It's too complicated to take regex seriously, I think ...
< $, (. n-dru).
:
$output = preg_replace(<<<'REGEX'
(\$\K\s*((?:[^<$\s]+|(?!\s+[<$])\s+)*)\s*(?=(?:<(*ACCEPT)|\$|$)(*SKIP)(*F))
# \$\K => avoid the leading $ in the match
# ((?:[^<$\s]+|(?!\s+[<$])\s+)*) => up to $ or <, excluding surrounding spaces
# (?=(?:<(*ACCEPT)|\$|$)(*SKIP)(*F)) => accept matches with <, reject these without
|(?!^)<\K\s*((?:[^<$\s]+|(?!\s+[<$])\s+)*)\s*(\$|)
# (?!^) => to ensure we are inside $ ... $
# <\K => avoid the leading < in the match
|[^$]+(*SKIP)(*F)
# skip everything outside $ ... $
)x
REGEX
, " $1$2 $3", $your_input);
: https://regex101.com/r/fP9aG5/2
, $x<y<z$ = > $x < y < z$ ( $ x < y < z $), . preg_replace_callback:
$output = preg_replace_callback(<<<'REGEX'
(\$\K\s*((?:[^<$\s]+|(?!\s+[<$])\s+)*)\s*(?=(?:<(*ACCEPT)|\$|$)(*SKIP)(*F))
|(?!^)<\K\s*((?:[^<$\s]+|(?!\s+[<$])\s+)*)\s*(\$|)
|[^$]+(*SKIP)(*F))x
REGEX
, function($m) {
if ($m[1] != "") return "$m[1] ";
if ($m[3] != "") return " $m[2]$m[3]";
return " $m[2] ";
}, $your_input);
$your_input :
random < test
nope $ foo $ bar < a $ qux < biz $fx<hk$
$foo<bar<baz$ foo buh < bar < baz $
$ foo $ a < z $ a < b < z $
preg_replace_callback, , :
random < test
nope $ foo $ bar < a $qux < biz$fx<hk$
$foo<bar<baz$foo buh < bar < baz$
$ foo $ a < z $a < b < z$
+2