tags:

views:

66

answers:

2

Hello,

I have a string to check and if it is only numbers and digits perform another action else exit;

$data = 123412347JB91742F;

 if(preg_match('/[A-Z1-9]/', $data )) {
  echo $data;

} 
else { 
  exit; 
}

this works fine but if i add anything to $data like $ or any other thing it still prints the value what is wrong with code?

/////////////////// edit ///////////////

$data = preg_replace('/-/', '', '1234-1234-JB91-8742F');

if(preg_match('/^[A-Z1-9]+$/', $data )) { echo $data; } else { exit; }

Thank You.

+2  A: 

Your regular expression just checks if there is at least one character of that set. Try this regular expression instead:

/^[A-Z1-9]+$/

The anchors ^ and $ mark the start and end of the string.

Gumbo
+2  A: 
  1. Your regex will match every string containing a digit or "normal" character.
  2. $data needs to be in quotes.

Your code should look like this:

preg_match('/^[A-Z1-9]+$/', $data)

Do you want to match zeros as well as lower case characters? Then your regex should look like this:

preg_match('/^[A-Z0-9]+$/i', $data)
Residuum