我制作了一个标有“页面编号”的文本框。
用户可以按任何顺序(如1, 3, 6 )输入页码。
如果用户输入了1, 4, 2, 6-8, 10,我想要处理这个问题。然后我应该知道用户选择了页面号1, 2, 4, 6, 7, 8, 10。
这意味着用户还可以输入范围以及逗号分隔的数字,就像我们打印文档时给出的页码一样。
也可以更改页面的顺序数。例如,5, 6, 4-8, 1。数字可以重复,但我只需要唯一的页码。
我如何在PHP中做到这一点?提前谢谢。
发布于 2012-08-10 05:54:59
以下是攻击计划:
我将设置为assoc数组,当我向其添加一个数字时,我会将其设置为键。例如。
$pageNumbers[$number] = true;下面是代码:
$pageNumberStr = $_REQUEST['pageNumberStr'];
$components = explode(",", $pageNumberStr);
$pageNumbers = array();
foreach ($components as $component) {
$component = trim($component);
if (preg_match('/^\d+$/', $component)) {
$pageNumbers[$component] = true;
} else if (preg_match('/^(\d+)-(\d+)$/', $component, $matches)) {
$first = min($matches[1], $matches[2]);
$last = max($matches[1], $matches[2]);
for ($i = $first; $i <= $last; $i++) {
$pageNumbers[$i] = true;
}
}
}
$pageNumbers = array_keys($pageNumbers);
sort($pageNumbers);发布于 2012-08-10 06:17:27
我不认为我的答案像emuranos那样好,但我的回答是,我不知道如何使用正则表达式(这也要求它们以min-max而不是max-min输入页面范围,并在它们之间输入所有数字",“):
$answer = array();
$text = "1, 4, 2, 6-8, 10, 2-4, 9, 10";
$nums = explode(", ", $text);
foreach ($nums as $value)
{
if (strpos($value, "-") == false)
if (!in_array($value, $answer)) array_push($answer, $value);
else
{
$newVal = split("-", $value);
for ($i = $newVal[0]; $i <= $newVal[1]; $i++)
if (!in_array($i, $answer)) array_push($answer, $i);
}
}
sort($answer);发布于 2012-08-10 05:51:18
您可以爆破文本框值和数组排序,然后用范围从该数组中查找值,如果不存在则按数组中的值进行排序,然后再对其进行排序。我觉得这样就行了。
https://stackoverflow.com/questions/11896095
复制相似问题