PHP面试题??PHP字符串翻转函数

WBOY
Release: 2016-06-23 14:29:44
Original
1135 people have browsed it

  偶遇一PHP面试题,题目很短,也很常见,但更容易出错,题目如下

  如何实现字符串翻转?
Copy after login

  第一反应,当然是strrev函数啦,这么容易的题目还放在面试里考,真不嫌麻烦啊?但是看了网上的答案后,发现自己错了~~~

  strrev函数对英文很好用,直接可以实现字符串翻转,但是面对中文呢?肯定都是乱码,对于这样的问题有很多,比如strstr,substr等函数都是这样的。还好PHP提供了mb_类的函数实现不同编码、不同语言之间的相互转换等操作。下面是我写的PHP字符串翻转函数(mb_类的函数需要开启一个mb_string实现)。

<?PHP function getRev($str,$encoding='utf-8'){ $result = ''; $len = mb_strlen($str); for($i=$len-1; $i>=0; $i--){ $result .= mb_substr($str,$i,1,$encoding); } return $result; } $string = 'OK你是正确的Ole'; echo getRev($string); ?>
Copy after login

  输出结果:

---------- PHP Debugger ---------- elO的确正是你KO Output completed (0 sec consumed) - Normal Termination
Copy after login

 

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