我怎样才能得到给定元素左边和右边的数字?

How i can get the numbers on the left and the right of the given element?

给定一个字符串:

$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 appear ...我需要看看,','

之间的 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() 会有所帮助,但考虑到限制条件:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

给出索引在字符串中的位置,尝试使用 str_replace()

删除 ','
// removes ',' from string
str_replace(',', '', $pages); 

结果为“123456”,然后 strpos($pages, $number) 将为您提供索引位置 4 的索引。给定验证(边界检查)即。 > 0< strlen(..),可以用-1和+1得到上一个和下一个。

希望这对您有所帮助。