Home > Article > Backend Development > How to use reverse string to reverse Chinese in PHP
Reversing a string is the basic operation of a string. It is more commonly used to reverse numbers and English strings in a string. Chinese strings are rarely seen. This article will show you how to use the strrev() function to reverse a string.
Reverse English string:
<?php $string = 'This is manoj'; $n =strlen("$string"); For($i=1;$i<=$n;$i++) { $val= $string[-$i]; echo $val; } echo "<br>"; echo strrev($string); ?>
Reverse Chinese string:
<?php header("content-type:text/html;charset=utf-8"); $str = "欢迎来到这里!"; function cnstrrev($str){ $len = strlen($str); for($i = 0; $i < $len; $i++) { $char = $str{0}; if(ord($char) > 127) //ord()函数取得第一个字符的ASCII码,如果大于0xa0(127)的话则是中文字符 { $i+=2;//utf-8编码的情况下,一个中文字符占三个字节 if($i < $len) { $arr[] = substr($str, 0, 3);//utf-8编码的情况下,一个中文字符占三个字节 $str = substr($str, 3); } } else { $arr[] = $char; $str = substr($str, 1);//否则为非中文,占一个字符 } } return join(array_reverse($arr));//以相反的元素顺序返回数组: } // 输出反转的字符串 echo '反转前:'.$str.'<br><br>反转后:'.cnstrrev($str);
Output:
反转前:欢迎来到这里!反转后:!里这到来迎欢
Recommended: "php video tutorial 》《php tutorial》
The above is the detailed content of How to use reverse string to reverse Chinese in PHP. For more information, please follow other related articles on the PHP Chinese website!