How to match an exclamation mark (!) In PHP?

I want to combine words with a camel, starting with ! , for example !RedHat contained in $line . I am using php 5.3.10-1ubuntu2 with Suhosin-Patch (cli) .

I try the following things:

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

How to choose the right one ! in PHP regexp?

+7
source share
2 answers

You need to use delimiters in your regular expression - not alphanumeric as indicated in the error message:

 $line = preg_replace("/ !([AZ])/", " $1", $line); 

Note the / characters at the beginning and end of the regular expression string.

It should not be / - you can use # or even ! but if you use ! you will need to avoid ! char inside regex itself.

+6
source

Try the following:

 !\b([AZ][az]*){2,}\b 

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

-one
source

All Articles