Rakesh Sharma
Rakesh Sharma

Reputation: 13728

Regex to find not start and end with dot and allow some special character only not all

I am trying to match a string which is not start and and with (.)dot and allow some special char like underscore(_) in string i found dot match regex but not able to match special character what i have done

preg_match('/^(?![.])(?!.*[.]$).*$/', $str)

Not allowed

.example
example.
example?ghh. (or some more special char not allowed in string)

allowed

 exam.pl56e
    exmple_
    _example_
    exam_ple

So string will be

1. Not start with dot but in the middle can be a dot(.)
2. String Not allow special char (&%$#@) etc. But allow alpha numeric, underscore
3. Not end with dot(.)

It's matching start and end dot correctly but i need to improve it to not allow all special character like (!&%) etc. Just allow given special character. Thanks

Upvotes: 2

Views: 4333

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may use

'~^(?!\.)[\w.]*$(?<!\.)~'

See the regex demo

Details:

  • ^ - start of string
  • (?!\.) - a . cannot be the first char
  • [\w.]* - 0 or more letters, digits, _ or . chars (replace * with + to match at least 1 char in the string to disallow an empty string match)
  • $ - end of string
  • (?<!\.) - last char cannot be .

Upvotes: 5

Toto
Toto

Reputation: 91488

How about:

^\w[\w.]*\w$

This is matching alphanum or underscore, optional dot in the midle then alphanumeric or underscore.

NB: It matches strings greater or equal to 2 characters.

This one matches strings with at least one character long.

^(?!\.)[\w.]+$(?<!\.)

Upvotes: 1

volkinc
volkinc

Reputation: 2128

preg_match('/^[^.].*[^.]$/', $str)

if you need to avoid dot from a beginning and end of the string you want use the class [^.]

The .* tels you that you allow all chars in a string. If your goal is to restrict some chars inside a string you can use [^......] before dot.

preg_match('/^[^.][^?*].*[^.]$/', $str)

Upvotes: 0

Related Questions