Brandon Stephen Hayden Brandon Stephen Hayden - 7 months ago 13
PHP Question

PHP preg_match_all not returning values

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.

Answer

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) «?»
Comments