preg_match与php编译失败

I try to match this expression :

* ^X-Spam-Flag: YES

I use this code :

if(preg_match('\'* ^X-Spam-Flag: YES\'', $value))

But i have this error :

PHP Warning: preg_match(): Compilation failed: nothing to repeat at offset 0

Problem with regex and * and ^ but can i correct that ?

You are missing your delimiters.

Change to:

preg_match('#\'* ^X-Spam-Flag: YES\'#', $value)

Or maybe you need:

preg_match('#\* \^X-Spam-Flag: YES#', $value)

You was near the solution, you have to escape ^ and * since these have a special meaning in a regex pattern:

if(preg_match('\'\* \^X-Spam-Flag: YES\'', $value))

If your escaped single quotes look strange and may be better replaced by / or ~ ... however these can be used as delimiters.

More informations about delimiters here: http://www.php.net/manual/en/regexp.reference.delimiters.php

To safely escape Regex special characters, you can simply use "preg_quote()", which adds backslashes in front of these characters.

if(preg_match('\'* ^X-Spam-Flag: YES\'', preg_quote($value)))