如何在 PHP 字符串中转义数学模式之外的特殊乳胶字符
how to escape special latex characters outside of math mode in a PHP string
假设
$string = " we will study integers & functions & matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ";
我想在数学模式之外转义特殊的乳胶字符(例如“&”),同时保留所有数学内容,因此所需的输出将是:
$string = " we will study integers \& functions \& matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ";
如果有人能指引我一个好的方向,我将不胜感激。谢谢
像这样:
$text = ' we will study integers & functions & matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ';
$pattern = <<<'EOD'
~
[$&%#_{}^\%]
(?:
(?<=$)
(?:
$ [^$]*+ (?:$(?!$)[^$]*)*+ $$ # display math mode (unofficial syntax)
|
[^$]+ $ # ordinary math mode
) (*SKIP)(*F)
|
(?<=\)
(?:
\[ [^\]*+ (?>\(?!])[^\]*)*+ \] # display math mode (square brackets)
|
\( [^\]*+ (?>\(?!\))[^\]*)*+ \ \) # ordinary math mode (parenthesis)
|
begin{(verbatim|math|displaymath|equation)} .*? \end{\g{-1}}
|
verb\*?(.).*?\g{-1} | [\@ ]
|
[a-z]+ (?:\[ [^]]* ] | {([^{}]*(?:{(?-1)}[^{}]*)*+)} | \( [^)]* \) | \s+ )* # latex keyword
)
(*SKIP)(*F)
|
(?<=%) \N* # comments
(*SKIP)(*F)
)?
~xs
EOD;
$text = preg_replace_callback($pattern, function ($m) {
return ($m[0] == '\') ? '\textbackslash{}' : '\' . $m[0]; }, $text);
该模式使用回溯控制动词组合 (*SKIP)(*F)
。当回溯机制发生并遇到 (*SKIP)
标记时,正则表达式引擎停止其回溯遍历并在目标字符串中的当前位置(在 (*SKIP)
位置)重试整个模式,因此所有字符都匹配在 (*SKIP)
标记之前被忽略并且不重试。 (*F)
(或(*FAIL)
)强制启动回溯机制的模式失败。
请注意,如果您不希望 PHP 将所有反斜杠解释为转义序列,则字符串必须用单引号引起来。
假设
$string = " we will study integers & functions & matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ";
我想在数学模式之外转义特殊的乳胶字符(例如“&”),同时保留所有数学内容,因此所需的输出将是:
$string = " we will study integers \& functions \& matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ";
如果有人能指引我一个好的方向,我将不胜感激。谢谢
像这样:
$text = ' we will study integers & functions & matrices such as $$\begin{tabular}{ccc} a & b & c \ a & b & c \ \end{tabular}$$ ';
$pattern = <<<'EOD'
~
[$&%#_{}^\%]
(?:
(?<=$)
(?:
$ [^$]*+ (?:$(?!$)[^$]*)*+ $$ # display math mode (unofficial syntax)
|
[^$]+ $ # ordinary math mode
) (*SKIP)(*F)
|
(?<=\)
(?:
\[ [^\]*+ (?>\(?!])[^\]*)*+ \] # display math mode (square brackets)
|
\( [^\]*+ (?>\(?!\))[^\]*)*+ \ \) # ordinary math mode (parenthesis)
|
begin{(verbatim|math|displaymath|equation)} .*? \end{\g{-1}}
|
verb\*?(.).*?\g{-1} | [\@ ]
|
[a-z]+ (?:\[ [^]]* ] | {([^{}]*(?:{(?-1)}[^{}]*)*+)} | \( [^)]* \) | \s+ )* # latex keyword
)
(*SKIP)(*F)
|
(?<=%) \N* # comments
(*SKIP)(*F)
)?
~xs
EOD;
$text = preg_replace_callback($pattern, function ($m) {
return ($m[0] == '\') ? '\textbackslash{}' : '\' . $m[0]; }, $text);
该模式使用回溯控制动词组合 (*SKIP)(*F)
。当回溯机制发生并遇到 (*SKIP)
标记时,正则表达式引擎停止其回溯遍历并在目标字符串中的当前位置(在 (*SKIP)
位置)重试整个模式,因此所有字符都匹配在 (*SKIP)
标记之前被忽略并且不重试。 (*F)
(或(*FAIL)
)强制启动回溯机制的模式失败。
请注意,如果您不希望 PHP 将所有反斜杠解释为转义序列,则字符串必须用单引号引起来。