如何在PHP中匹配感叹号(!)?

kop*_*por 7 php regex

我希望匹配!!RedHat包含在内的骆驼套词$line.我正在使用php 5.3.10-1ubuntu2 with Suhosin-Patch (cli).

我正在尝试以下事情:

  • $line = preg_replace(" !([A-Z])", " $1", $line);
    • 结果: PHP Warning: preg_replace(): No ending delimiter '!' found
  • $line = preg_replace(" \!([A-Z])", " $1", $line);
    • 结果: PHP Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
  • $line = preg_replace(" [!]([A-Z])", " $1", $line);
    • 结果: PHP Warning: preg_replace(): Unknown modifier '('
  • $line = preg_replace(" [\!]([A-Z])", " $1", $line);
    • 结果: PHP Warning: preg_replace(): Unknown modifier '('

如何!在PHP regexp中匹配正确的方法?

Ale*_*s G 6

您需要在正则表达式中使用分隔符 - 非字母数字,因为错误消息指出:

$line = preg_replace("/ !([A-Z])/", " $1", $line);
Run Code Online (Sandbox Code Playgroud)

注意/正则表达式字符串开头和结尾的字符.

这些不一定是/- 你可以使用#甚至!- 但如果你使用!那么你将需要逃避!正则表达式本身内的字符.