10

I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.

I tried to search on google but I could not find anything usefull.

Can anybody help?

Thank you !

1
  • 3
    Which loser down-voted my question ? Commented Dec 27, 2012 at 16:06

3 Answers 3

5

Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'

So:

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good
}

Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.

Sign up to request clarification or add additional context in comments.

2 Comments

What happens if "preg_match('/^[A-Za-z0-9_-]*$/', $yourString" returns 0, as in it doesnt match ? You still validate it, right ?
Good clarification. I edited the example. This way if preg_match is anything but 0 or FALSE, you are good to go.
0
$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1

$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0

Comments

0

You can use preg_replace($pattern, $replacement, $subject):

if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
  echo "Detect non valid character inside the string";
}

The idea is to remove any valid chars, if the result is NOT empty do the code.

Comments

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.