Tony Smith
Tony Smith

Reputation: 73

How to use preg_match to match everything except numbers in PHP?

Here is my code:

//Validate names have correct characters
if (preg_match("/^[a-zA-Z\s-]+$/i", $_POST['first']) == 0) {
  echo '<p class="error">Your first name must only include letters,
        dashes, or spaces.</p>';
  $okay = FALSE;
}

if(preg_match("/^[a-zA-Z\s-]+$/i", $_POST['last']) == 0) {
  echo '<p class="error">Your last name must only include letters, 
        dashes, or spaces.</p>';
  $okay = FALSE;
}

How do I modify this code so that it accepts everything except numbers?

Upvotes: 1

Views: 5774

Answers (2)

Suamere
Suamere

Reputation: 6258

Vedran was most correct. The \d means digits, and the capital \D means NOT digits. So you would have:

if (preg_match("/\d/i", $_POST['first']) > 0) {
  echo '<p class="error">Digits are not allowed, please re-enter.</p>';
  $okay = FALSE;
}

The above means... If you find any digit... do your error. aka: allow everything except digits.

HOWEVER... I believe you need to re-think your idea to allow "Everything Except digits." You typically don't want the user to enter Quotes or Special ACII Characters, but it appears you want them to be able to enter -!@#$%^&*()_+=|}{\][:;<>?,./~

That seems like a long list, but compared to the complete list of possible characters, it isn't that long. So even though it seems like more work, you might want to do that:

if (preg_match("/[^-~`!@#$%^&*()+={}|[]\:;<>?,.\w]/i", $_POST['first']) > 0) {
echo '<p class="error">ASCII and Quotes are not accepted, please re-enter.</p>';
$okay = FALSE;
}

Neither one of these have the Beginning/End-Line special characters, because you are looking anywhere in the string for any occurance of (or not of) these checks.

I changed the comparison operator to (if greater than) because we aren't looking for the lack of something required to throw an error anymore, we are looking for the existence of something bad to throw an error.

Also, I took the underscore out of the last regex there... because the Word Character (\w) includes digits, letters, and underscores. Lastly, the dash in the character-class has to be either FIRST or LAST in the list, or it sometimes throws errors or is accidentally mistaken as a range character.

Upvotes: 3

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28850

preg_match("/^[^0-9]*$/", $string)

accepts everything but numbers.

Upvotes: 1

Related Questions