Home > Article > Backend Development > A brief discussion on detailed explanation of php string reversal examples
This article mainly shares with you a brief discussion on PHP string reversal. Questions often encountered in interviews have good reference value. I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.
1. Single-byte string reversal
php provides the function strrev() for string reversal
$str = 'abcdef'; echo strrev($str);
2. For multi-byte strings containing Chinese, you need to use mb_substr()
$str = '字符串反转'; function rev($str, $encoding = 'utf-8'){ $len = mb_strlen($str); $result = ''; for ($i = $len-1; $i>=0; $i--){ $result.= mb_substr($str,$i,1,$encoding); } return $result; } echo rev($str);
3. Algorithm to realize first exchange
$str = 'abcdefg'; $len = strlen($str); $times = $len/2; for($i = 0;$i <= $times; $i++ ){ $tmp = $str[$i]; $str[$i] = $str[$len-$i-1]; $str[$len-$i-1] = $tmp; } echo $str;
Related recommendations:
php method to achieve string reversal output_PHP tutorial
String processing - php to achieve string reversal [head and tail exchange]
javascript Three methods to achieve string reversal_javascript skills
The above is the detailed content of A brief discussion on detailed explanation of php string reversal examples. For more information, please follow other related articles on the PHP Chinese website!