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: 247
  • Last Modified:

PHP Regular expressions - checking for only numbers and letters, ignore whitespace

Hi all,

I have the following:

function isValid($str) {
    return !preg_match('/[^A-Za-z0-9]/', $str);

Open in new window

which works fine with input with no spacing but how can I amend this to ignore whitespacing?

Desired use cases:
'this is a sentance with spaces' returns true
'this is a sentance££ with spaces$$' returns false
'thisisasentancewithnospaces' returns true
'thisisasentance%%%withnospaces' returns false
2 Solutions
Ovid BurkeCreative DirectorCommented:

function isValid($str) {
    return !preg_match('/[^A-Za-z0-9\s*]/', $str);

Open in new window

Terry WoodsIT GuruCommented:
function isValid($str) {
    return !preg_match('/[^A-Za-z0-9\s]/', $str);

You don't want an asterisk in there too as it will be treated as a literal asterisk.
dolythgoeAuthor Commented:
Thanks guys

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