Page 1 of 1
Difficulty matching the plus sign
Posted: Sun Nov 23, 2008 3:54 pm
by Brew
Hi
I am using the following pattern with preg_replace to remove unwanted characters
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
Re: Difficulty matching the plus sign
Posted: Mon Nov 24, 2008 3:38 am
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.
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.
Re: Difficulty matching the plus sign
Posted: Wed Nov 26, 2008 4:30 am
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?
Re: Difficulty matching the plus sign
Posted: Mon Dec 01, 2008 2:08 pm
by prometheuzz
Brew wrote:Hi
I am using the following pattern with preg_replace to remove unwanted characters
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:
+