我有一个循环遍历数据的正则表达式,如下所示
23:10:54 User Name 1 has looted 598 x Dark Ochre
23:13:58 UserName 2 has looted 947 x Obsidian Ochre
22:55:29 User Name3 has looted 1509 x Onyx Ochre
22:55:29 User Name3 has looted 3 x Obsidian Ochre
正则表达式(下)正确地将数据解析为值$value['userName'];
$re = '/^(?<timeMined>[0-9]{2}:[0-9]{2}:[0-9]{2}) # timeMined
\s+
(?<userName>[\w\s]+) # user name
\s+(?:has\s+looted)\s+ # garbage text between name and amount
(?<amount>\d+) # amount
\s+x\s+ # multiplication symbol
(?<item>.*?)\s*$ # item name (to end of line)
/xmu';
preg_match_all($re, $sample, $matches, PREG_SET_ORDER);
在下面的数据集中,有 3 个不同的用户名。我正在尝试遍历数据并将用户名添加到数组中(如果它尚不存在)。这是我目前拥有的。但是,我只得到 1 个结果,用户名 3。我对问题出在哪里感到困惑。
foreach ($matches as $value){
$userName = $value['userName'];
echo $userName."<BR>";
$userNameArray = array();
if (in_array($userName, $userNameArray)){
}
else {
array_push($userNameArray, $userName);
}
}
echo "<BR><BR><BR><BR><BR>";
foreach ($userNameArray as $value){
echo $value."<BR>";
}
此代码导致以下结果。顶部是准确的,但是底部缺少两个用户名
User Name 1
UserName 2
User Name3
User Name3
User Name3