我如何与PHP交换每两个数字在一个长数字值?你可以看到下面的例子:
例子:12345678
已转换为:21436587
首先必须转换为数组。使用
$array=explode("",$string);
你会得到{"1","2","3","4","5","6","7","8"}
然后调用下面的函数。
function swapNumbers($array){
$finalString="";
for($i=0;$i<sizeOf($array);$i++){
if($i!=0){
if($i%2==0){
$finalString.=$array[$i-1].$array[$i];
}
}
if($i==sizeOf($array)-1 && $i%2==1){
$finalString.=$array[$i];
}
}
return $finalString;
}
你会得到21436587
您可以(例如)使用循环和substr_replace()函数来解决这个问题。注意奇数字符
正如评论中提到的,请先尝试一些代码
<?php
class SwapableNumber
{
private $value;
private $swapSize;
public function __construct($value, $swapSize = 2)
{
$this->value = $value;
$this->swapSize = $swapSize;
}
public function swap()
{
$result = [];
$valueParts = str_split($this->value, $this->swapSize);
foreach ($valueParts as $part) {
// for last part and if it is not complete in size
// (e.g 2 number for a swapSize == 2), it returns
// it unchanged. If the requirement is that partial
// groups of digits should be reversed, too, remove the
// conditional block.
if (strlen($part) < $this->swapSize) {
$result[] = $part;
break;
}
$result[] = strrev($part);
}
return implode('', $result);
}
}
// Example usage (by default the swap size is 2 so it swaps every 2 digits):
$n = new SwapableNumber(12345678);
echo $n->swap();