php正则表达式的间歇性未知修饰符错误

时间:2012-03-17 18:16:22

标签: php regex

我正在使用正则表达式将@page中使用的边距CSS复制到正文。对于大多数HTML页面,代码替换效果很好。

然而,在某些页面上,我收到一个未知的修饰符错误,我无法确定问题所在的正则表达式。

非常感谢有关如何解决此错误的任何指导。

错误:消息: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; }

1 个答案:

答案 0 :(得分:1)

您可以在将preg_quote($body[0], '%')放入preg_replace之前致电{{3}}。几分钟前,其他人已经发布了这个答案,但现在似乎已经消失了。

编辑2:preg_quote实际上可以工作,如下面由ridgerunner所指出的。

由于您没有使用任何元字符,因此使用str_replace代替preg_replace可能更容易?