2015-08-24 31 views
1

假設如何逃生的數學模式之外的特殊乳膠字符在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}$$ "; 

如果有人可能會導致我在往好的方向發展,我將非常感激。 THX

回答

2

事情是這樣的:

$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將所有反斜槓解釋爲轉義序列,則該字符串必須包含在單引號之間。

+0

你真了不起!謝謝你,它工作得很好。 – userX