首页 > 解决方案 > 如何反转字符串的两个字符?

问题描述

我想在 PHP 中反转字符串的两个字符。例如50378f8f3750帮助我。

$str= User::where('id',$userid)->pluck('card_id');
$num = strrev($number);
echo $num;

这个功能反转很好,但我想反转两个字符而不是一个字符。

我的功能是给我输出示例:12345to543210但我希望它像 103254.

标签: phplaravelreverse

解决方案


你可以试试这个:

$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

推荐阅读