Home  >  Article  >  Backend Development  >  A brief discussion on detailed explanation of php string reversal examples

A brief discussion on detailed explanation of php string reversal examples

小云云
小云云Original
2018-01-13 13:07:411829browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn