php正则表达式不允许字符串中的DOT

Here is my code at the moment, allowing ONLY a-z and 0-9. If I wanted a similar regExp that will NOT allow any string containing a dot (.) how would I have to modify it?

if ( preg_match('/^[a-z0-9_]+$/',$myExtraField) == false ) {

This is inside a symfony2 form class, not sure whether the regExp is the same as flat PHP hence I included my present regExp... never had the time to dive into regExp and hardly ever use it.

The simplest check you could do would be

strpos($myExtraField, ".") === false

If you really wanted to use a regex, you could invert preg_match("/\./") or just do a check like preg_match("/^[^.]*$/")

FWIW, your regex also allows the underscore ("_") character.

If you want a regex that will disallow a dot, you can simply test for the existence of a dot, and change the sense of your test:

if ( preg_match('/\./',$myExtraField) == true ) {

Alternately, it may be more performant to use strpos:

if (strrpos($myExtraField, '.') == -1) { 

then no '.' is present...

If you must use a regex, then use the following:

if (preg_match('/^[^.]*$/',$myExtraField)) {
    // doesn't contain period
} else {
    // does contain period
}

Expression:

^[^.]*$

Visualization:

Regular expression visualization

In a regex, you can exclude a character by using the ^.

So /^[^.]+$/ will match any string that do not contain any dot.

  • The first ^ means 'start of the string'
  • [^.]+ means at leat one char
  • $ means end of the string

Use a * instead of the + if you want to match the empty string.