A brief discussion on detailed explanation of php string reversal examples

小云云
Release: 2023-03-19 14:20:02
Original
1812 people have browsed it

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);
Copy after login

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);
Copy after login

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;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!