ObiHill
ObiHill

Reputation: 11876

PHP Regex all characters except numbers and boolean

I'm using PHP and I have developed a script to sanitize a JSON string.

One step in the process is to prevent numbers and booleans from being double-quoted explicitly.

Below is my regex pattern to exclude numbers.

/\:[\s\n\t]*([^0-9\{\}\[\],\"]+)[\s\n\t]*/i

However, I'm trying to enhance it so that it includes boolean as well i.e. true and false. Without this, any booleans will be double-quoted (which I want to avoid).

Any ideas how I can improve the regex above?

Thanks.

Upvotes: 0

Views: 781

Answers (1)

mario
mario

Reputation: 145482

You can use an ?! assertion to exclude booleans from being matched by your character class blacklist.

 /\:[\s\n\t]*(?!true|false)([^0-9\{\}\[\],\"]+)[\s\n\t]*/i

Btw, the character class as it is will fail for floats. Also I'm not entirely convinced of your "sanitization" approach. It seems you only postprocess some bare array attributes here. (And it'll furthermore fail if they are composed of more than one word that isn't enclosed in dquotes.)

Upvotes: 1

Related Questions