开发者

Basic regexp help

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 = "/^[R开发者_C百科AL][0-9 .-]+$/i";

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

Cheers Ben


[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.


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.


/^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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜