Home >Backend Development >PHP Tutorial >A brief discussion on PHP string reversal. Problems often encountered in interviews

A brief discussion on PHP string reversal. Problems often encountered in interviews

jacklove
jackloveOriginal
2018-07-02 17:54:122879browse

The editor below will share 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 and take a look.

1. Single-byte string reversal

php provides for string reversal The function strrev()

$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;

The above article briefly talks about PHP string reversal that is often encountered in the interview. 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. .

Articles you may be interested in:

Detailed explanation of the type declaration of functions in various versions of PHP

PHP explains the method of counting the number of occurrences of a number in a sorted array

PHP basic knowledge code summary


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