jsuissa
jsuissa

Reputation: 1762

Intermittent unknown modifier error with php regex

I'm using regex to copy the margin CSS used in @page to body. For most HTML pages the code replacement works well.

However on some pages I get an unknown modifier error and I can't determine where the issue is with the regex.

Any guidance on how to resolve this error would be much appreciated.

Error: Message: preg_replace() [function.preg-replace]: Unknown modifier ';'

Code excerpt:

    $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

$body[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; }

Upvotes: 0

Views: 46

Answers (1)

user1233508
user1233508

Reputation:

You could call preg_quote($body[0], '%') before putting it into preg_replace. Someone else had posted this answer just minutes earlier, but it seems to be gone now.

Edit 2: preg_quote actually can work, as pointed out below by ridgerunner.

Since you are not using any metacharacters, it might be easier to just use str_replace instead of preg_replace?

Upvotes: 1

Related Questions