PHP preg_match_all不返回值


PHP preg_match_all not returning values

我有一个regex,它检查长度在4到25个字符之间的用户名,后面跟着任何可选的空格和/或一个逗号。正如您可能已经猜到的,这将用于通过键入"Username1、Username2、Username3"等内容向几个人发送个人消息。

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

regex似乎正在完成它的工作,尽管当我使用preg_match_all()并尝试对所有值进行排序时,它不会向浏览器返回任何内容。我怀疑我对preg_match_all有些误解,因为我的regex似乎在工作。

您的正则表达式在用户名上缺少捕获组(['w]{4,25}),请尝试以下操作:

<?
$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
*/

实时演示


Regex解释:

(['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) «?»