user188962
user188962

Reputation:

How can I check with a regex that a string contains only certain allowed characters?

I need a special regular expression and have no experience in them whatsoever, so I am turning to you guys on this one.

I need to validate a classifieds title field so it doesn't have any special characters in it, almost.

Only letters and numbers should be allowed, and also the three Swedish letters å, ä, ö (upper- or lowercase).

Besides the above, these should also be allowed:

Upvotes: 24

Views: 71493

Answers (4)

Kae Cyphet
Kae Cyphet

Reputation: 185

There is a security flaw in the accepted answer:

^[\s\da-zA-ZåäöÅÄÖ&()+%/*$€é,.'"-]*$

This will generate a true response for empty strings as * is for 0 or more occurrences.

Here is a more secure version:

^[\s\da-zA-ZåäöÅÄÖ&()+%/*$€é,.'"-]+$

The + responds true to 1 or more occurrences.

More information can be found at https://regexr.com/

Upvotes: 7

Chris Van Opstal
Chris Van Opstal

Reputation: 37587

Try this:

^[\s\da-zA-ZåäöÅÄÖ&()+%/*$€é,.'"-]*$

Breakdown:

^ = matches the start of the string

[...]* = matches any characters (or ranges) inside the brackets one or more times

$ = matches the end of the string

Updated with all the suggestions from the comments. Thanks guys!

Upvotes: 38

dnagirl
dnagirl

Reputation: 20446

PHP has a variety of functions that can help with text validation. You may find them more appropriate than a straight regex. Consider strip_tags(), htmlspecialchars(), htmlentities()

As well, if you are running >PHP5.2, you can use the excellent Filter functions, which were designed for exactly your situation.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

^[\sa-zA-Z0-9åäö&()+%/*$€é,.'"-]*$

will match all the required characters.

In PHP:

if (preg_match('#^[\sa-zA-Z0-9åäö&()+%/*$€é,.\'"-]*$#i', $subject)) {
 # Successful match
} else {
 # Match attempt failed
}

Upvotes: 0

Related Questions