簡體   English   中英

用環繞式PHP從字符串中獲取X個字符

[英]get X characters from string with php with wraparound

我有一個PHP問題,其中我有一串數字:

即/ 1,2,3,4,5,6,7,8,9 ... X

我知道第一個數字,必須創建一個長X的字符串,以便它可以環繞

例如,如果我的字符串是1,2,3,4,5並且我的第一個數字是4-我需要返回字符串:

4,5,1,2,3

我想創建一個函數來實現這一點-任何幫助都將非常有用!

謝謝。

<?php
function MyWrap($string, $first)
{
    $splitHere = strpos($string, $first);
    return rtrim(substr($string, $splitHere).','.substr($string, 0, $splitHere), ',');
}

echo MyWrap('1,2,3,4,5', '4');
?>

輸出:

4,5,1,2,3
function wrapAroundNeedle($myString, $myNeedle)
{
  $index = strrpos($myString, $myNeedle);
  return substr($myString, $index).",".substr($myString, 0, $index - 1);  
}

如何自己動手。 請注意,在PHP 4中,strrpos僅允許$ needle的單個字符。

string substr ( string $string , int $start [, int $length ] )

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

http://php.net/manual/en/function.substr.php

http://php.net/manual/en/function.strrpos.php

$pos = strpos($string,$first_number);
return substr($s,$pos).','.substr($s,0,$pos);

我相信我明白你的需要 - 試試這個:

function numsWrap($firstNumber, $total) {
  $newStr = "";

  $inc = $firstNumber;
  for($i = 0; $i < $total+1; $i++) {
    if($i == 0) {
      $newStr .= $inc;
    } else {
      if($inc == $total) {
    $newStr .= "," . $inc;

    $inc = 0;
      } else {
    $newStr .= "," . $inc;
      }
    }

    $inc++;
  }

  return $newStr;
}

用法:

echo numsWrap(5, 10);
5,6,7,8,9,10,1,2,3,4,5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM