2012-03-17 35 views
0

我正在使用正則表達式將@page中使用的頁邊空白CSS複製到正文。對於大多數HTML頁面,代碼替換效果很好。php正則表達式的間歇性未知修飾符錯誤

但是在一些頁面上,我得到一個未知的修飾符錯誤,我無法確定問題與正則表達式的位置。

有關如何解決此錯誤的任何指導將不勝感激。

錯誤:消息:preg_replace()[function.preg-replace]:未知修飾符';'

代碼摘錄:

$pattern ='%@page \{.*?\}%s'; 
    preg_match($pattern, $output, $page); 

    $pattern = '%margin:.*?\;%s'; 
    preg_match($pattern, $page[0], $margin); 

    $pattern = '%(?=body).*?\}%s'; 
    preg_match($pattern, $output, $body); 


    $new_margin = $margin[0] . "\n" . "}"; 
    $new_body = preg_replace("%\}%", $new_margin, $body[0]); 

    $output = preg_replace('%'.$body[0].'%', $new_body, $output); //ERROR HERE 

$體[0]:

body { font-family: 'Josefin Slab', sans-serif; font-size: 9pt; height: 100%; min-height: 100%; display:block; } 

$ new_body:

body { font-family: 'Josefin Slab', sans-serif; font-size: 9pt; height: 100%; min-height: 100%; display:block; margin: .7in .3in .3in .4in; } 
+0

如果您轉義模式字符串中的所有反斜槓,錯誤是否消失?即使用'%margin:。*?\\;%s'' – bearver 2012-03-17 18:21:10

+0

我曾嘗試過。無論如何,我添加了第一個反斜槓來逃避; – jsuissa 2012-03-17 18:31:12

回答

1

你可以把它變成preg_replace之前調用preg_quote($body[0], '%')。其他人在幾分鐘前發佈了這個答案,但現在似乎已經消失了。

編輯2:preg_quote實際上可以工作,正如ridgerunner下面指出的那樣。

由於您沒有使用任何元字符,因此使用str_replace而不是preg_replace可能更容易?

+0

Thx。嘗試preg_quote沒有運氣,但要去嘗試你的str_replace想法。 – jsuissa 2012-03-17 18:28:42

+0

str_replace做到了:'$ output = str_replace($ body [0],$ new_body,$ output);' – jsuissa 2012-03-17 18:35:27

+1

'preg_quote($ body [0],'%')'將會正確執行這個技巧,但是您需要提供''%''作爲可選的第二個參數。 – ridgerunner 2012-03-17 19:02:25

相關問題