Search code examples
phpregexpreg-matchdigits

Can't have only digits in URL subpart sequence


I want to change regex so it matches if class group doesn't have only digits between two slashes:

$regex = "~^upload/(?<class>[/a-z0-9_\.]+)/(?<id_table>\d+)$~";

preg_match($regex, "upload/.bes/.ur/13"); // returns true
preg_match($regex, "upload/.tables/fewf/.u23ser/15"); // returns true
preg_match($regex, "upload/.t/les2/.uer/11"); // returns true
preg_match($regex, "upload/1.tales/.user2/01"); // returns true

preg_match($regex, "upload/23/21"); // returns false
preg_match($regex, "upload/.tables/00/31"); // returns false
preg_match($regex, "upload/6/.uer/q/51"); // returns false

Solution

  • You may use

    $regex = "~^upload/(?<class>(?!\d+/)[a-z0-9_.]+(?:/(?!\d+/)[a-z0-9_.]+)*)/(?<id_table>\d+)$~";
    

    See this regex demo.

    The class named group pattern matches

    • (?!\d+/)[a-z0-9_.]+ - one or more lowercase ASCII letters, digits, _ or ., but not if all these chars are digits
    • (?:/(?!\d+/)[a-z0-9_.]+)* - zero or more repetitions of
      • / - a / char
      • (?!\d+/)[a-z0-9_.]+ - one or more lowercase ASCII letters, digits, _ or ., but not if all these chars are digits