假设我有这个用户列表:
Michael (43)
Peter (1) (143)
Peter (2) (144)
Daniel (12)
最右边一组括号中的数字是用户编号。
我想循环每个用户,并获得列表中最高的用户编号,在本例中为144
。我该怎么做?我确信这可以用某种regexp来完成,但我不知道怎么做。我的循环很简单:
$currentUserNO = 0;
foreach ($users as $user) {
$userNO = $user->NameUserNo; // NameUserNo is the string to be stripped! ex: "Peter (2) (144)" => 144
if ($userNO > $currentUserNO) {
$currentUserNO = $userNO;
}
}
echo "The next user will be added with the user number: " . $currentUserNO + 1;
您可以使用类似的正则表达式
/'(('d+)')$/
^ glued to the end of the string
^^ closing parentheses
^^^ the number you want to capture
^^ opening parentheses
以捕获字符串末尾最后一组括号/中的数字。
但是您也可以使用一些基本的数组和字符串函数:
$parts = explode('(', trim($user->NameUserNo, ' )'));
$number = end($parts);
其分解为:
- 从结尾处修剪右括号和空格(严格地说,从开头和结尾处,也可以使用
rtrim()
) - 在左括号上爆炸
- 获取结果数组的最后一个元素
如果你对正则表达式不满意,你就不应该使用它们(并开始认真学习它们*,因为它们非常强大,但很神秘)。
同时,您不必使用regex来解决问题,只需使用(假设NameUserNo只包含列表的一行):
$userNO = substr(end(explode('(',$user->NameUserNo;)),0,-1);
它应该更容易理解。
*有没有一个好的在线交互式regex教程?
我认为您要查找的正则表达式是:
.+'(('d+)')$
它应该选择所有字符,直到它到达括号中的最后一个数字。
可以用来提取数字的PHP代码是:
$userNO = preg_replace('/.+'(('d+)')$/', '$1', $user);
我还没有测试过,但它应该为用户Michael
将$userNO
设置为43
,为用户Peter
设置143
,依此类推
我想这基本上就是你想要的:
<?php
$list = array();
foreach $users as $user) {
preg_match('/$([a-zA-Z]+).*'([1-9]+')$/', , $tokens);
$list[$tokens[2]] = $tokens[1];
}
ksort($list);
$highest = last(array_keys($list));
echo "The next user will be added with the user number: " . $highest++;
使用正则表达式很容易做到这一点。
foreach ($users as $user) {
# search for any characters then a number in brackets
# the match will be in $matches[1]
preg_match("/.+'(('d+)')/", $user->NameUserNo, $matches);
$userNO = $matches[1];
if ($userNO > $currentUserNO) {
$currentUserNO = $userNO;
}
}
由于regexs使用贪婪匹配,.+
(意味着搜索一个或多个字符)将在输入字符串达到括号中的数字之前尽可能多地获取输入字符串。
我是PHP的新手,但你不能用吗
$exploded = explode(" ", $user->NameUserNumber);
$userNo = substr(end($exploded), 1,-1);