Jump to content

Regular expression


Andy17

Recommended Posts

Hey

 

I'm pretty new to regular expression, so I might have made a silly mistake. I want to check if there are any symbols/special characters (not letters or numbers) in a string. I have the code below.

 

function validateKeywords($kw) {
	if (preg_match("/[^A-Za-z0-9]/", $kw)) {
		echo 'validation of keywords failed<br />';
		return false; // String contains symbols (not letters or numbers) - incorrect format!
	}
	else {
		echo 'validation of keywords succeeded<br />';
		return true; // Correct format
	}
}

// Testing
validateKeywords('some random string I wrote for testing purposes'); // should succeed
validateKeywords('some random 10 string I wrote for testing purposes 2010'); // should succeed
validateKeywords('some random, string, I wrote for 19 testing purposes'); // should fail
validateKeywords('some, random, string I wrote, for testing purposes'); // should fail

 

The problem is that all 4 calls return false and print that the validation failed. So, where did I mess up? :)

 

Thanks!

Link to comment
Share on other sites

correct me if I am wrong but [^A-Za-z0-9] means your string may not have any alphanumeric caracters.

So your doing the exact opposite.

 

and since all your strings have them all are False.

 

removing the Carrot  ^  inside the [ ] will do the trick. I would also add also add \s for the spaces

 

this could be what your looking for.

/^([a-zA-Z0-9\s])*$/

 

realise that dots are not allowed, so if someone ends his sentence with one it will be false.

If you want to include dots add  \.

Link to comment
Share on other sites

A space isn't a valid input in that. If you do this: validateKeywords('thisisastring');, it returns true.

 

Wow, I didn't even think of that. Thanks for pointing that out.

 

oh i saw a small mistake it should be this:

/^[A-Za-z0-9\s]*$/

 

Smooth, that seems to work. Thanks a lot. :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.