Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace $x<y$ by $x < y$

Tags:

I want to search in text for the less than sign < between dollar signs like $x<y$ and replace it by $x < y$.

I am using mathjax and less than sign causes some problems in 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 am not sure if this is a good solution. I am new to programming:)

Thank you for your help.

like image 788
mac Avatar asked Jul 28 '16 14:07

mac


2 Answers

I edited my previous answer - now try this:

$text = preg_replace('/\$([^$< ]+)<([^$< ]+)\$/','$$1 < $2$', $text);

DEMO

like image 169
n-dru Avatar answered Oct 11 '22 16:10

n-dru


This is far too complicated to be seriously done with regex, I think...

As long as you have a fixed number of < between the $ signs, it's easy (See the answer from n-dru).

But here you are:

$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);

See also: https://regex101.com/r/fP9aG5/2

I realize, you requested for $x<y<z$ => $x < y < z$ (instead of $ x < y < z $), but this is not doable with normal replacement patterns. Would need preg_replace_callback for that:

$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);

I've tried $your_input with:

random < test
nope $ foo $ bar < a $ qux < biz $fx<hk$
$foo<bar<baz$ foo  buh < bar < baz $
$ foo $ a < z $ a < b < z $

with this preg_replace_callback, I get, as expected:

random < test
nope $ foo $ bar < a $qux < biz$fx<hk$
$foo<bar<baz$foo  buh < bar < baz$
$ foo $ a < z $a < b < z$
like image 26
bwoebi Avatar answered Oct 11 '22 15:10

bwoebi