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

时间:2021-05-24 22:26:43

I want to match camel cased words beginning with ! such as !RedHat contained in $line. I'm using php 5.3.10-1ubuntu2 with Suhosin-Patch (cli).

我想要匹配以驼峰开头的单词开头!比如!$ Line中包含的RedHat。我正在使用php 5.3.10-1ubuntu2和Suhosin-Patch(cli)。

I'm trying following things:

我正在尝试以下事情:

  • $line = preg_replace(" !([A-Z])", " $1", $line);
    • result: PHP Warning: preg_replace(): No ending delimiter '!' found
    • 结果:PHP警告:preg_replace():没有结束分隔符'!'发现
  • $ line = preg_replace(“!([A-Z])”,“$ 1”,$ line);结果:PHP警告:preg_replace():没有结束分隔符'!'发现
  • $line = preg_replace(" \!([A-Z])", " $1", $line);
    • result: PHP Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
    • 结果:PHP警告:preg_replace():分隔符不能是字母数字或反斜杠
  • $ line = preg_replace(“\!([A-Z])”,“$ 1”,$ line);结果:PHP警告:preg_replace():分隔符不能是字母数字或反斜杠
  • $line = preg_replace(" [!]([A-Z])", " $1", $line);
    • result: PHP Warning: preg_replace(): Unknown modifier '('
    • 结果:PHP警告:preg_replace():未知修饰符'('
  • $ line = preg_replace(“[!]([A-Z])”,“$ 1”,$ line);结果:PHP警告:preg_replace():未知修饰符'('
  • $line = preg_replace(" [\!]([A-Z])", " $1", $line);
    • result: PHP Warning: preg_replace(): Unknown modifier '('
    • 结果:PHP警告:preg_replace():未知修饰符'('
  • $ line = preg_replace(“[\!]([A-Z])”,“$ 1”,$ line);结果:PHP警告:preg_replace():未知修饰符'('

How is the correct way to match ! in PHP regexp?

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

2 个解决方案

#1


6  

You need to use delimiters in your regex - non-alphanumeric, as the error message states:

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

$line = preg_replace("/ !([A-Z])/", " $1", $line);

Notice the / characters at the beginning and end of the regex string.

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

These don't have to be / - you could use # or even ! - but if you use ! then you'll need to escape the ! char inside the regex itself.

这些不一定是 - 你可以使用#甚至! - 但如果你使用!那么你需要逃避!正则表达式内部的char。

#2


-1  

Try this:

尝试这个:

!\b([A-Z][a-z]*){2,}\b

Live preview: http://regexr.com?30a95 (check global and multiline).

实时预览:http://regexr.com?30a95(检查全局和多行)。

#1


6  

You need to use delimiters in your regex - non-alphanumeric, as the error message states:

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

$line = preg_replace("/ !([A-Z])/", " $1", $line);

Notice the / characters at the beginning and end of the regex string.

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

These don't have to be / - you could use # or even ! - but if you use ! then you'll need to escape the ! char inside the regex itself.

这些不一定是 - 你可以使用#甚至! - 但如果你使用!那么你需要逃避!正则表达式内部的char。

#2


-1  

Try this:

尝试这个:

!\b([A-Z][a-z]*){2,}\b

Live preview: http://regexr.com?30a95 (check global and multiline).

实时预览:http://regexr.com?30a95(检查全局和多行)。