Difficulty matching the plus sign

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Brew
Forum Newbie
Posts: 1
Joined: Fri Nov 21, 2008 5:07 am

Difficulty matching the plus sign

Post by Brew »

Hi

I am using the following pattern with preg_replace to remove unwanted characters

Code: Select all

#[^-a-zA-Z0-9+_.,!*()$]#
This works perfectly apart from it removes the plus sign (+) from a string, even though I have specified it in the pattern.

Can someone tell me what I am doing wrong please ?

Any help would be much appriciated.

Thanks,
Brew
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Difficulty matching the plus sign

Post by GeertDD »

The + metacharacter (and most other metacharacters) lose their special meaning inside a character class. So don't put it in there and it's fixed.

Code: Select all

#[^-a-zA-Z0-9_.,!*()$]#
Note that by adding a + modifier to the whole character class in this case, you will speed up the regex a bit since the amount of replaces that the regex needs to handle will go down. It replaces more characters at once then.

Code: Select all

#[^-a-zA-Z0-9_.,!*()$]+#
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: Difficulty matching the plus sign

Post by mintedjo »

Brew wrote: I am using the following pattern with preg_replace to remove unwanted characters
So you want to keep the plus signs and A-Z etc?
GeertDD wrote:The + metacharacter (and most other metacharacters) lose their special meaning inside a character class. So don't put it in there and it's fixed.
I don't get it... How does removing + from the negated character class solve that problem?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Difficulty matching the plus sign

Post by prometheuzz »

Brew wrote:Hi

I am using the following pattern with preg_replace to remove unwanted characters

Code: Select all

#[^-a-zA-Z0-9+_.,!*()$]#
This works perfectly apart from it removes the plus sign (+) from a string, even though I have specified it in the pattern.

...
That is not possible. The regex you posted will NOT remove the '+'-s from your string.
When you execute this:

Code: Select all

echo preg_replace('#[^-a-zA-Z0-9+_.,!*()$]#', '', '#+%');
it will print: +
Post Reply