2

Right now, i'm trying to create a PHP Regular Expression with these following conditions:

  • Accepts all UTF-8 characters
  • Space between words are allowed, how only 1 space and not multiple.
  • Allow all symbols for example: !#$%^&*()_-={}[] except: "@"
  • No trailing spaces after or before the string.
  • Range should be 2-16 characters including spaces
  • And must contain at least 2 letter characters in the string.

Here is the Regex I have drawn up so far:

/^(?=.{2,16}$)[^@\s]+(?:\h[^@\s]+)*$/um

So far this does all of the following except that it doesn't meet the last condition which is that it must contain at least 2 letters. For example:

"..He" //should be true

"He$*" //should be true

".." //should be false

"*%" //should be false

"!#$%^&*()" //should be false since there is no letters

"$$tonyMoney™" //should be true

"أنا أحب جا™" //should be true

"To" //should be true

Any help is appreciated! Thank you!

4

1 Answer 1

3

You can actually use

/^(?![^@]*@)(?!.*\s\s)(?=(?:\P{L}*\p{L}){2})\S.{0,14}\S$/us 

Here is a regex demo (modified a bit for a demo with multiline text).

For the regex to work with Unicode strings, you need to specify the /u modifier. For the . to match any character, you need to use /s modifier.

The regex breakdown:

  • ^ - start of string
  • (?![^@]*@) - make sure there is no @ in the string
  • (?!.*\s\s) - make sure there are no 2 consecutive whitespaces
  • (?=(?:\P{L}*\p{L}){2}) - make sure there is at least 2 Unicode letters
  • \S.{0,14}\S - 2 symbols are obligatory, must start and end with a non-whitespace, from 2 to 16 characters long
  • $ - end of string
Sign up to request clarification or add additional context in comments.

2 Comments

Note that "أنا أحب جافا سكريبت™" is longer than 16 symbols.
@CasimiretHippolyte: True, have not thought about that. Fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.