Home > php教程 > PHP源码 > PHP字符串翻转实例代码

PHP字符串翻转实例代码

PHP中文网
Release: 2016-05-25 17:09:58
Original
981 people have browsed it

 字符翻转对于php处理来说,简直是小菜一碟,php的字符串函数strrev就可以处理例如

 字符翻转对于php处理来说,简直是小菜一碟,php的字符串函数strrev就可以处理例如
Copy after login

但有时候面试的时候往往需要我们自己来写个函数来实现跟strrev同样的效果,其实这也不难,例如:

/**
 * 实现字符串翻转的函数
 * @param string $str 要处理的字符串
 * @return string 翻转成功的字符串
*/
function reverse($str){
 if($str == ''){
 return null;
}
 if(strlen($str) == 1){
 return $str;
}else{
 $string ="";
for($i=1;$i<=strlen($str);$i++){
 $string .=substr($str,-$i,1);
}
 return $string;
}
}

echo reverse("Hello World!"); //输出结果为"!dlroW olleH"
Copy after login

                   


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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template