Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
PHP Regex: allowed no more 3 digits but any count for another chars

I need to modify the exp:

/^[-\p{L}\d]+$/u

The purpose is to allow maximum 3 digits in whole string, but letter chars and dashes should be allowed without quantity restrictions. No matters where digits are located within string. For instance:

test345  //this should match
345te-st  //this should match
3454dtest  //this shouldn\'t match

I have already tried some patterns, but is don't work properly:

/^[-\p{L}\d{0,3}]+$/u
/^[-\p{L}]+[\d]{0,3}+$/u
/^([-\p{L}]+)([\d]+){0,3}$/u
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The patterns that you tried don't work properly matching max 3 digits anywhere in the string because between the start and end anchors:

  • This notation is fully in a character class [-\p{L}\d{0,3}]+ which matches repeating 1+ times any of the listed characters between [...] (So there is no digit limit due to the +)
  • This notation [-\p{L}]+[\d]{0,3}+ matches 1+ times [-\p{L}] followed by 0-3 consecutive digits (So the digits can not be at the start for example)
  • This notation ([-\p{L}]+)([\d]+){0,3} uses 2 capture groups, but the order here is also 1+ times [-\p{L}] and 0-3 consecutive digits (only here is the capture group repeated)

If empty strings are also allowed:

^(?:[\p{L}-]*\d){0,3}[\p{L}-]*$
  • ^ Start of string
  • (?:[\p{L}-]*\d){0,3} Match 0-3 times optional repetitions of [\p{L}-] and a single digit
  • [\p{L}-]* Match optional repetitions of [\p{L}-] at the end
  • $ End of string

Regex demo

Else you can assert that the string is not empty using (?!$)

^(?!$)(?:[\p{L}-]*\d){0,3}[\p{L}-]*$

Regex demo

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!