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
https://forums.phpfreaks.com/topic/213827-regular-expression/
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
https://forums.phpfreaks.com/topic/213827-regular-expression/#findComment-1112980
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
https://forums.phpfreaks.com/topic/213827-regular-expression/#findComment-1115171
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.