1

I have a regex that checks for a username between 4 and 25 characters in length, followed by any optional spacebars and/or a single comma. As you may have guessed this is to be used for sending personal messages to several people by typing something like "Username1, Username2, Username3" ect.

$rule = "%^\w{4,25}( +)?,?( +)?$%";
preg_match_all($rule, $sendto, $out);
foreach($out[1] as $match) {
    echo $match;
}

The regex seems to be doing its job, although when I use preg_match_all(), and attempt to sort through all the values, it will not echo anything to the browser. I suspect that I am misunderstanding something about preg_match_all, since my regex seems to be working.

1
  • you should test if preg_match_all() was successful or not before attempting to consume $out. Commented May 3, 2016 at 0:32

1 Answer 1

3

Your regex is missing a capture group ([\w]{4,25}) on the usernames, try this:

<?
$users = "Username1, Username2      , Username3       ";
preg_match_all('/([\w]{4,25})(?:\s+)?,?/', $users, $result, PREG_PATTERN_ORDER);
foreach($result[1] as $user) {
    echo $user;
}
/*
Username1
Username2
Username3
*/

Live Demo


Regex Explanation:

([\w]{4,25})(?:\s+)?,?

Match the regex below and capture its match into backreference number 1 «([\w]{4,25})»
   Match a single character that is a “word character” (Unicode; any letter or ideograph, any number, underscore) «[\w]{4,25}»
      Between 4 and 25 times, as many times as possible, giving back as needed (greedy) «{4,25}»
Match the regular expression below «(?:\s+)?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character that is a “whitespace character” (any Unicode separator, tab, line feed, carriage return, vertical tab, form feed, next line) «\s+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “,” literally «,?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that fixed my problem. I appreciate the help, I am new to regex and it can be overwhelming. I've been trying to fix the wrong thing for the last several hours it seems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.