Php 如何获得给定元素左右两侧的数字?
给定一个字符串:Php 如何获得给定元素左右两侧的数字?,php,arrays,string,pagination,numbers,Php,Arrays,String,Pagination,Numbers,给定一个字符串: $pages = "1,2,3,4,5,6"; 创建一个函数,用于获取给定元素左侧和右侧的数字。 我预计这将带来: pagination(1); // array('prev' => null, 'next' => 2); pagination(2); // array('prev' => 1, 'next' => 3); pagination(6); // array('prev' => 5, 'next' => null); 我不想使
$pages = "1,2,3,4,5,6";
创建一个函数,用于获取给定元素左侧和右侧的数字。
我预计这将带来:
pagination(1); // array('prev' => null, 'next' => 2);
pagination(2); // array('prev' => 1, 'next' => 3);
pagination(6); // array('prev' => 5, 'next' => null);
我不想使用explode(),我只想使用
仅使用字符串操作函数。
这是我试过的,但它是8 apear。。。我要看看,5之间的
<?php
$number = "5";
$pages = "1,2,3,4,5,6";
$x = strpos($pages, $number);
echo $x;
?>
还没有测试过,但我认为这可以给你一个想法 这不适用于大于等于10的数字
function get_near_elems($number = 5)
{
$pages = "1,2,3,4,5,6";
$x = strpos($pages, $number);
if($x == 0)
return array('prev' => null, 'next' => $pages[$x]);
else if($x == (strlen($pages) - 1))
return array('prev' => $pages[$x - 2], 'next' => null);
else
return array('prev' => $pages[$x - 2], 'next' => $pages[$x + 2]);
}
由于这看起来像是家庭作业,我建议您在这里看到一些东西并对其进行修改。我将使用类似于以下函数的函数,只需要确保pages变量在函数中可访问
function getPreviousAndNext($number)
{
$location = strpos($pages, number);
$previous = ($number > 0 ? substr($pages, ($location - strlen($number - 1)), strlen($number - 1) + 1) : null);
$next = ($number == strlen($pages) - 1 ? null : substr($pages, ($location + strlen($number + 1)) + 1, strlen($number + 1));
return [
"previous" => $first,
"next" => $last
]
}
explode()
会有帮助,但考虑到以下限制:
混合strpo(字符串$haystack,混合$needle[,int$offset=0])
给出索引在字符串中的位置,请尝试使用删除“”
这将导致“123456”,然后strpos($pages,$number)
将为您提供索引位置4的索引。给定验证(边界检查),即>0
和
,您可以使用-1和+1获得上一个和下一个
希望这有帮助。
explode()
是一个字符串操作函数…我强烈建议使用explode,否则当你有9个以上的数字时,要想正确使用它会非常复杂。事实上,这可能是一个500字的示例。闻起来很像家庭作业或基本编程考试,尤其是“我不想使用explode()”部分…只是说…可能是您需要的。$pages[$x-1]
(与+1相同)将导致“,“正在选择,因为这是字符串中的下一个字符。所以它必须是-2/+2,这对9以上的数字不起作用……是的,我修正了它。他还没有指定它是否必须对大于10的数字起作用。是的,对不起。仍然会被大于9的数字打破,因为那将是两个字符长。对,如果数字永远都不大于9,那就好了。只是看不到不使用数组的理由。
// removes ',' from string
str_replace(',', '', $pages);