0

I'm trying to perform an input check in php for name tag, which consists of English, Chinese, and numbers.

"/^[A-z0-9\p{Han}]{2,12}$/u";

I would like to achieve the name tag rule of 12 units of character where a Chinese character is 2 unit and English/Number is 1 unit.

Can a regular expression match for such rule?

To give you some example:

六 matches because as of \p{Han} and 2 units
六1 matches because of 0-9, \p{Han}, and 3 units
1 does not match as of 1 unit
一二三四五六七 does not match as of 14 units
Noble Dinasaur
  • 97
  • 1
  • 11
  • 1
    It is best to combine the regex with a bit of code. Count all Chinese chars, count all ASCII letter/digits, and calculate the "unit" length. Note [you should not use `[A-z]`](https://stackoverflow.com/questions/29771901/why-is-this-regex-allowing-a-caret/29771926#29771926), use `[A-Za-z]`. – Wiktor Stribiżew Aug 21 '18 at 08:06

1 Answers1

0

After some tinkering, I have a solution

"/^([A-Za-z0-9]{2}|\p{Han})([A-Za-z0-9]{1,2}|\p{Han}){0,5}$/u";

The first part ([A-Za-z0-9]{2}|\p{Han}) matches 2 units, either 1 Chinese character or 2 Eng/Num.

immediacy follow by ([A-Za-z0-9]{1,2}|\p{Han}){0,5} that matches 0 unit to 5 Chinese character or 10 Eng/Num character. Total of 12 units.

Thanks for the note of Should not use [A-z]

Noble Dinasaur
  • 97
  • 1
  • 11