Home > Backend Development > PHP Tutorial > PHP string reversal is often encountered in interviews

PHP string reversal is often encountered in interviews

韦小宝
Release: 2023-03-19 13:56:01
Original
1704 people have browsed it

The editor below will share with you a brief discussion on php stringreversal, problems often encountered in PHP interviews, which has a good reference value and I hope it will be helpful to everyone. Friends who are interested in PHP, please follow the editor to read this article

1. Single-byte string reversal

php provides the function for string reversal strrev()

$str = 'abcdef';
echo strrev($str);
Copy after login

2. For multi-byte characters containing Chinese The string needs 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 the 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

The above article briefly talks about PHP string reversal that is often encountered in interviews. This is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

Related recommendations:

Steps to implement orderly splitting of PHP strings

The most complete PHP string processing function

php string is converted to lowercase function strtolower()

The above is the detailed content of PHP string reversal is often encountered in interviews. 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