以下短文是PHP中的正则表达式匹配特殊字符的办法及特殊情况解决方法。原文出自《PHP and MySQL Web Development(Third Edition)》,水平较菜,如有错译欢迎指正...

原文:Matching Literal Special Characters
If you want to match one of the special characters mentioned in the preceding sections,such as .,{,of $,you must put a backslash() in front of it.If you want to represent a backslash,you must replace it with two backslash(\).
Be careful to put your regular expression patterns in single-quoted strings in PHP.Using regular expressinos in double-quoted PHP strings adds unnecessary complications.PHP also uses the backslash to escape special characters--such as a backslash.If you want to match a backslash in your pattern,you need to use two to indicate that it is a literal backslash,not an escape code.
Similarly,if you want a literal backslash in a double-quoted PHP string,you need to use two for the same reson.The somewhat confusing,cumulative result of these rules is that a PHP string that represents a regular expression containing a literal backslash needs four backslashes.The PHP interpreter will parse the four backslashes as two.Then the regular expression interpreter will parse the two as one.
The dollar sign is also a special character in double-quoted PHP strings and regular expressions.To get a literal $ matched in a pattern,you would need "\$".Because this string is in double quotation marks,PHP will parse it as $,which the regular expression interpreter can then match against a dollar sign.

译文:特殊字符的原义匹配
  如果想匹配之前提到的如 .,{,$,等特殊字符(在正则表达式中有特殊意义的字符),就必须在该字符前加反斜杠(),(C中管它叫‘转义符’)如果想表示这个反斜杠(),就在他前面再加个反斜杠,即改成(\)。
  必须注意的是在PHP中要尽量把正则表达式放在单引号(')中。如果把正则表达式放在双引号里则会引起一些不必要的麻烦。在PHP的正则表达式中也要使用反斜杠()来‘掩盖’一些特殊的字符--像反斜杠()自身。在表达式中如想匹配一个反斜杠(),也必须使用两个反斜杠()来表示它是原义的反斜杠(),而不是转义符。
  类似的原因,把反斜杠()放在双引号中时也要使用两个反斜杠()来转义。令人困惑的是,根据以上规则,在PHP中的正则表达式里要表示一个反斜杠()就要四个反斜杠()。PHP解析器会将四个反斜杠()解析成两个。之后正则解析又将之解析成一个。
  美圆符$在PHP字串和正则表达式中也是个有特殊意义的字符。如需匹配$的原义字符,就必须写成"\$".因为它在双引号里,PHP会将之解析为$,然后正则解析就会将它匹配为美圆符(而不是表示‘字符串的结束位置’)。
/*cpyeh
  而把正则表达式放在单引号里就没有以上的问题,所以尽量不要把正则表达式放在双引号中,免得自找麻烦。
*/