0

For example I want .brewpixels and brewpixels. to echo

your username is invalid

If the dot is anywhere between the first and last letter the script should echo

your username is good

How do I change my regex to accomplish this?

$username = 'brew.pixels';

if(preg_match('/(^\d|[^\w])/', $username)){
    echo 'your username is invalid';
} else {
    echo 'your username is good';
}
dockeryZ
  • 3,981
  • 1
  • 20
  • 28
brewpixels
  • 311
  • 1
  • 5
  • 19

2 Answers2

3

The following will match strings that begin or end with a dot

(the trick is to escape the dot since it has special meaning in regex)

/^\.|\.$/

DEMO

With additional conditions only alpha num underscore and dot within the body:

/^(\.[\w.]+|[\w.]+\.)$/

DEMO

Simply to replace in your given code:

if(preg_match(regexToMatchBadWords, $username)){
    echo 'your username is invalid';
} else {
    echo 'your username is good';
}

Or, you can match directly the correct words by forcing the first & last chars to be alpha-num-underscore and the inner body to accept dots too:

/^(\w[\w.]+\w)$/

DEMO

Which reverses the logic in your code:

if(preg_match(/^(\w[\w.]+\w)$/, $username)){
    echo 'your username is good';
} else {
    echo 'your username is invalid';
}
Enissay
  • 4,969
  • 3
  • 29
  • 56
  • This works but I loose functionality. The regex I provided only allows alphanumeric characters and underscores. I want the final regex to do the same, and prevent dots at the beginning and end of a string. – brewpixels Feb 11 '16 at 00:32
  • @brewpixels You allow alphaNum chars + underscore + dots within the body right ? – Enissay Feb 11 '16 at 00:38
  • yes that's right. But alphaNum chars and underscore can be outside of the body. – brewpixels Feb 11 '16 at 00:50
  • Try my last edit, if it doesnt work, i'll need examples to work on ! (be fast, i'll have to leave in 30min xD ) – Enissay Feb 11 '16 at 00:53
1

I am not sure if you are saying that you want it to have other regex info but you can do:

if (preg_match('/^\./', $username) || preg_match('/\.$/', $username) {
  echo 'invalid';
}

This will make .brew and brew. fail.

I forgot about the pipe character, see Enissays answer for the correct simpler way.

Fireynis
  • 407
  • 6
  • 13