1

I want to check a string to allow only a-z A-Z 0-9 . / ? & but I'm unsure how exactly to use preg_match().

If you could also explain what each part of the code is I'd appreciate it! (ie why do you add /^ and how to you add a /)

Thanks

2 Answers 2

4

Here it is:

$input = 'Hello...?World';
$regex = '~^[a-z0-9&./?]+$~i';

if (preg_match($regex, $input)) {
  echo "yeah!";
}

You can build your own character classes and validate strings this way.

Explanation:

~
^                        # string start
[                        # start character class 
  a-z                    # letters from a to z
  0-9                    # digits from 0 to 9
  &./?                   # &,.,/ and ? chars
]                        # end character class
+                        # repeat one or more time
$                        # string end
~ix
Sign up to request clarification or add additional context in comments.

1 Comment

.?/ are not meta characters in a character class and do not need escaping. / is not a meta character anyway, it only needs escaping if you use it as a delimiter. Every character has its literal meaning except ]\^- Also you would be better to do if (!preg_match('~[^a-z0-9&./?]~i')) for simplicity and to give PCRE less to do, I feel.
-1
if ( preg_match('[^a-zA-Z0-9./?&]', 'azAZ09./?&') ) {
     //found a character that does not match!
 } else //regex failed, meaning all characters actually match

Pretty similar to ioseb's, but you need to include A-Z because uppercase is different from lowercase. He has written a great guide to the characters already so I'll just present an alternative regex.

I rely on negation instead (the ^ at the start, which when included at the start of a character class '[]', it has a different meaning instead), followed by the string of "allowed characters".

That way, if the regex finds anything that isn't an allowed character (the [] means one character), it'll stop parsing and return true, which means an invalid string was found.

4 Comments

using [ and ] as delimiters is kinda awkward IMHO.
What do you mean by delimiter? It's just a set of possible values for one character. In any case, what would you have instead?
regex pattern in PHP have : 2 "delimiters" (I don't know if that's the good word to use) that surround it (usually "/", "#" or "~"). And if you didn't know that, you should know that [^xxx] means "everything but xxx". Therefore, you're twicely wrong.
Thanks for the heads-up about the delimiter, but if you read clearly, the negation is the exact point of the regex. It's trying to find a non-match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.