我想在PHP中反转字符串的两个字符。例如50378f
至8f3750
,请帮助我。
$str= User::where('id',$userid)->pluck('card_id');
$num = strrev($number);
echo $num;
此功能可以很好地反转,但是我想反转两个字符而不是一个字符。
我的功能是给我输出示例:12345
至543210
,但我希望它像
103254
。
答案 0 :(得分:2)
您可以尝试以下方法:
$originalString = '23242526';
$arrayWith2CharsPerElement = str_split($originalString, 2);
$arrayWithReversedKeys = array_reverse($arrayWith2CharsPerElement);
$newStringInReverseOrder = implode($arrayWithReversedKeys);
echo $newStringInReverseOrder; //will print 26252423
编辑:更改了处理奇数字符串的方法
$string = '121314152';
$countDown = strlen($string);
$substrLength = 2;
$reverseString = '';
while ($countDown > 0) {
$startPosition = $countDown -2;
if ($countDown == 1) {
$startPosition = 0;
$substrLength = 1;
}
$reverseString .= substr($string, $startPosition, $substrLength);
$countDown -= 2;
}
echo $reverseString; //will print 524131211
答案 1 :(得分:0)
您可以尝试
function strReverse($string) {
$newString = "";
if ((strlen($string) % 2) != 0) $string = "0". $string;
for($pos = 0; $pos < strlen($string); $pos++) {
$chr = substr($string, $pos, 1);
if (($pos % 2) == 0) {
$tmp = $chr;
} else {
$newString .= $chr . $tmp;
$tmp = "";
}
}
if ($tmp != "") $newString .= $tmp;
return $newString;
}
echo strReverse('12345'); // result 103254
答案 2 :(得分:0)
我已经重写了该函数,您可以通过修改$ noOfChar来定义要反转的字符长度。
例如,如果您设置$ noOfChar = 3,则12345结果将为1004325。
function strReverse($string) {
$newString = "";
$noOfChar = 2;
$remain = strlen($string) % $noOfChar;
$string = str_repeat("0", $remain) . $string;
$segment = "";
for($pos = 0; $pos < strlen($string); $pos++) {
$segment = $segment . substr($string, $pos, 1);
if ((($pos + 1) % $noOfChar) == 0) {
$newString .= strrev($segment);
$segment = "";
}
}
if ($segment != "") $newString .= strrev($segment);
return $newString;
}
echo strReverse('12345');
答案 3 :(得分:0)
您可以将以下功能用于两个插槽的反向字符串。
function reverseByTwoCharacters($string)
{
$stringReversed = "";
if (!empty($string)) {
$stringLength = strlen($string);
if ($stringLength % 2 == 0) {
$splittedString = str_split($string, 2);
} else {
$splittedString = str_split(substr($string, 1), 2);
array_unshift($splittedString, $string[0]);
}
$reverseString = array_reverse($splittedString);
$stringReversed = implode($reverseString);
}
return $stringReversed;
}
$string = "1234567890";
echo reverseByTwoCharacters($string);
// Output
9078563412