[英]get X characters from string with php with wraparound
I have a PHP problem where I have a string of numbers: 我有一个PHP问题,其中我有一串数字:
ie/ 1,2,3,4,5,6,7,8,9...... X 即/ 1,2,3,4,5,6,7,8,9 ... X
I know the first number and have to create a string X long so that it wraps around 我知道第一个数字,必须创建一个长X的字符串,以便它可以环绕
for example if my string is 1,2,3,4,5 and my first number is 4 - i need to return the string: 例如,如果我的字符串是1,2,3,4,5并且我的第一个数字是4-我需要返回字符串:
4,5,1,2,3 4,5,1,2,3
I'd like to create a function to achieve this - any help would be great! 我想创建一个函数来实现这一点-任何帮助都将非常有用!
Thanks. 谢谢。
<?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');
?>
Output: 输出:
4,5,1,2,3
function wrapAroundNeedle($myString, $myNeedle)
{
$index = strrpos($myString, $myNeedle);
return substr($myString, $index).",".substr($myString, 0, $index - 1);
}
How to roll your own. 如何自己动手。 Note that strrpos only allows single characters for $needle in php 4.
请注意,在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.substr.php
http://php.net/manual/en/function.strrpos.php http://php.net/manual/en/function.strrpos.php
$pos = strpos($string,$first_number);
return substr($s,$pos).','.substr($s,0,$pos);
I believe I understand what you need - try this: 我相信我明白你的需要 - 试试这个:
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;
}
Usage: 用法:
echo numsWrap(5, 10);
5,6,7,8,9,10,1,2,3,4,5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.