Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

php - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 .

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...