Tutorial :PHP preg_match: a pattern which satisfies all MySQL field names (including 'table.field' formations)


i need a pattern which satisfies mysql field names, but also with the option of having a table name before it


mytable.myfield  myfield  my4732894__7289FiEld  

here's what i tried:

$pattern = "/^[a-zA-Z0-9_]*?[\.[a-zA-Z0-9_]]?$/";  

this worked for what i needed before, which was just the field name:

$pattern = "/^[a-zA-Z0-9_]*$/";  

any ideas why my addition isnt working?

maybe i'm making up regex, so i'll explain what i added... the first '?' is to say that it isn't greedy, ie. it will stop if the next part, namely "[.[a-zA-Z0-9_]]?" is satisfied. now, that second part is just the same as the first except it is optional (hence the '?' at the end) and it starts with a period (hence the '[.' and ']' wrapping my old clause. and obviously, the "^" and "$" rep the beginning and end of the string

so... any ideas?

(also, i'm a tad confused as to why i need to put in those "/"s in the begining/end anyways, so if you could tell me why it's required, that'd be awesome)

thanks a lot! (and thanks for reading this all if you actually did... it's quite a ramble)


[...] is used to construct a character class. Use (?:...) for grouping.

BTW, \w is equivalent to [a-zA-Z0-9_], so

$pattern = "/^\\w+(?:\\.\\w+)?$/"  

Note that I have also replaced *? with +. Since \w will never match a ., so it's non-greedy matching is not needed (*? â†' *). But I don't think .field should be valid, so a + should be used instead of *.


Field names (and table names) can contain almost any character. The only characters field names don't support are NULL (0x00) and trailing spaces. Table names (and db names) are a little more limiting in that they can also not have a /, \ or .... The only requirement is that you wrap the identifiers with "`" backtick quotes. If the identifier contains a backtick, escape it with another backtick...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »