PHP preg_match_all不返回值

时间:2016-05-03 00:24:21

标签: php arrays regex preg-match-all

我有一个正则表达式,用于检查长度为4到25个字符的用户名,后跟任何可选的空格键和/或单个逗号。您可能已经猜到,通过键入“Username1,Username2,Username3”等内容,可以将其用于向多人发送个人消息。

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

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

1 个答案:

答案 0 :(得分:3)

您的正则表达式缺少用户名上的捕获组([\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
*/

Live Demo

正则表达式解释:

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