Search code examples
phpregexpreg-match

Regex to match any character without trailing / leading whitespace + min / max length


I try to figure out how to match following values via preg_match using:

^[\S].*[\S]{3,10}$

Unfortunately, the min works from size of 4 and the max of 10 is being ignored at all as the pattern still machtes on a lenght of 11.

  1. Disallow leading and trailing spaces
  2. Allow any character inside
  3. Allow space within characters
  4. Enforce min of 3 and max of 10 (not working)

Testset that could be used with: https://www.phpliveregex.com

[
    [
        "Test",
        true
    ],
    [
        "Test Test",
        true
    ],
    [
        "Test-Test",
        true
    ],
    [
        "Test'Test",
        true
    ],
    [
        "Test,Test",
        true
    ],
    [
        null,
        false
    ],
    [
        "   ",
        false
    ],
    [
        " Test ",
        false
    ],
    [
        "12",
        false
    ],
    [
        "12345678901",
        false
    ]
]

Thanks for your help in advanced


Solution

  • You may use

    ^(?=.{4,10}$)\S.*\S$
    

    See regex demo

    Details

    • ^ - start of string
    • (?=.{4,10}$) - four to ten chars other than line break chars up to the end of string allowed
    • \S - a non-whitespace char
    • .* - 0 or more chars other than line break chars as many as possible
    • \S - a non-whitespace char
    • $ - end of string.