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

左心房为你撑大大i 提交于 2021-02-20 11:24:56

问题


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.


回答1:


I edited my previous answer - now try this:

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

DEMO




回答2:


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$



回答3:


I tried assemble this regular expression. Try it, if it suits your requirements.

$text = preg_replace("/\\$(.{1,20})<(.{1,20})\\$/", "\$$1 < $2\$", $text);

In this expression you have {1,20}, which you can use as parameter, how max long (in this case 20) can be your variable on left and right side.



来源:https://stackoverflow.com/questions/38639028/replace-xy-by-x-y

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!