Reputation: 3
So I am trying to do a relatively simple php regex to check wether a string contains one of these characters: .,%$@/0123456789 but I also want to check wether it contains a double backslash (I don't want it to evaluate to true if it only contains one backslash) and I can't figure out how to do it. Any help would be appreciated :)
Here is what I was using so far:
preg_match('/[.,%$@\/0-9]/',$string)
I am not sur how to include the '\\\\' for the double backslash.
Thanks in advance!
Upvotes: 0
Views: 247
Reputation: 32242
If the string must be made up of the characters you've given, but also must contain a double backslash, but not a single backslash, then as far as I can see you're going to need 3 regular expressions.
if (
(!preg_match('/[^.,%$@\/\\0-9]/', $string)) // fails if the string contains a character that is not allowed
&&
! (
preg_match('/\\/', $string) // contains at least one backslash
&&
!preg_match('/\\{2}/') // succeeds if the string contains a double-backslash
)
) { /* code */ }
If you try to combine all your rules into a single regex, you're gonna have a bad time.
There is also the drawback that once the string contains a double-backslash it can then have extra backslashes anywhere, ie '12\3456\78\90' is valid. If this is possible, but not permissible in the input then you might want to consider a regex that strictly checks the format rather than just testing for valid characters.
Upvotes: 0
Reputation: 2900
You're just looking for your character set or a double backslash, right? So:
preg_match('/[.,%$@\/0-9]|\\\\/',$string)
Where |
means "or".
Upvotes: 1