Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 19441
  • Last Modified:

PHP, check string for invalid character?

How can I check if a string contains symbols or weird characters like !@#$%^%^&&*(())-+=?><,.'"}{[]| etc?
2 Solutions
A better way to do things is to check that a string only contains the characters that are allowed. This is known as using a whitelist. Checking for illegal characters is known as using a blacklist. A whitelist is much easier to maintain than a blacklist.

Using regular expressions is a quick and easy way to check for character classes, so take a look at preg_match in the PHP documentation.

For instance, if your string only permitted letters, digits and standard spaces, you could use this to check that the string was valid:

$valid = preg_match('/^[a-z0-9 ]+$/', $string);

This does not allow an empty string, but if you change the + to a * the empty string will be permitted. If the string is valid, then $valid will equal true.

Regular expressions are not easy to grasp at first, but they are very powerful for string validation and manipulation.
Fortunately, there are libraries of well defined regular expressions from which to start with, so it isn't so intimidating.


Is an excellent place to start.
Forced accept.

EE Admin

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now