Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match exclamation mark (!) in PHP?

Tags:

regex

php

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).

I'm trying following things:

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

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

like image 666
koppor Avatar asked Mar 13 '12 09:03

koppor


People also ask

What does exclamation mark do in PHP?

It's a boolean tester. Empty or false. Show activity on this post. It's the not boolean operator, see the PHP manual for further detail.

What is exclamation point in regex?

! If an exclamation mark (!) occurs as the first character in a regular expression, all magic characters are treated as special characters. An exclamation mark is treated as a regular character if it occurs anywhere but at the very start of the regular expression.

What is the meaning of exclamation mark in programming?

In programming and scripting languages, the exclamation mark is used as "not." For example, "! =" also means not equal. See our operator definition for further information. Used to help identify a nonexecutable statement.


1 Answers

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.

like image 160
Aleks G Avatar answered Sep 22 '22 16:09

Aleks G