Home  >  Article  >  Backend Development  >  How to use reverse string to reverse Chinese in PHP

How to use reverse string to reverse Chinese in PHP

autoload
autoloadOriginal
2021-03-25 11:56:291998browse

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 = &#39;This is manoj&#39;;
$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 &#39;反转前:&#39;.$str.&#39;<br><br>反转后:&#39;.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!

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