tags:

views:

62

answers:

4

I am new to programming PHP and am trying to validate a field in a form.

The field if for a RAL color code and so would look something like : RAL 1001. so the letters RAL and then 4 numbers.

Can someone help me set them into a regular expression to validate them. i have tried this with no success:

$string_exp = "/^[RAL][0-9 .-]+$/i";

What can I say but sorry for being a complete NOOB at PHP.

Cheers Ben

+1  A: 

By removing redundant character classes, you'd get:

/^RAL \d{4}$/i

Note that using case-insensitive flag would make it match even such cases as Ral 1245 or raL 9875, for example.

SilentGhost
A: 
/^RAL [0-9]{4}$/

If you enter letters as they are, they are found as they are. If you enclose something in [], it means: "Search a single character that is one of these."

Therefore starting with a literal "RAL " finds a literal "RAL " (or "ral ", too, when you apply the i flag).

Boldewyn
+1  A: 

[RAL] will match just one character, either R, A or L, whereas you want to match the string "RAL". So you probably want something like this,

$string_exp = "/^RAL[0-9]{4}$/";

This will match "RAL1001", but not "RAL1","RAL 1001", "RAL12345", etc. If you wanted the space between RAL and the number, then also put that space into the regexp.

Rich Adams
Cheers worked a charm
casben79
A: 

Depends!

...
if( preg_match('/RAL\s*(\d{4})(?!\d)/', $name, $m) ) {
   echo $m[1];
}
...

This accepts 'someRAL 1234within text'
but doesn't accept 'RAL 12345'.

The exact regex depends entirely on your
context or specifications. You have to be more explicit in your question.

Regards

rbo

rubber boots
"The field if for a RAL color code and so would look something like : RAL 1001. so the letters RAL and then 4 numbers."I thought this was pretty explicit.
casben79
casben79, the formal problem is relatively simple, just /RAL\d{4}/. My question would be, *what else*? In what form does the data show up? Which of the following would be allowed or not?'RAL1234', 'RAL . 1234', 'RAL . . 1234', 'xxxRAL1234yyy' and so on.
rubber boots