Home >Backend Development >PHP Problem >What functions can the php strrev function achieve?

What functions can the php strrev function achieve?

青灯夜游
青灯夜游Original
2021-03-26 18:47:422592browse

strrev() is a built-in function in PHP that can reverse a string and return the reversed string; its syntax format is "strrev(string)", and the parameter string is used Specifies the string to be reversed and cannot be omitted.

What functions can the php strrev function achieve?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php strrev() function

trrev() function reverses a string. The syntax is as follows:

strrev(string)

Parameter description:

  • string: required. Specifies the string to reverse.

Return value: Returns the reversed string.

Example 1: Reverse English string

<?php
echo strrev("Hello world!"); 
?>

Output:

!dlrow olleH

Example 2: Reverse number

<?php  
$num = 134; 
echo "反转前:"; 
var_dump($num);
  
// 输出反转的数字
echo "反转后:"; 
var_dump(strrev($num));
?>

Output:

反转前:int(134)
反转后:string(3) "431"

Description: The strrev() function will convert the number into a numeric string and then reverse it.

Example 3: Reverse Chinese

<?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:

反转前:欢迎来到这里!

反转后:!里这到来迎欢

Explanation: When using the strrev() function to reverse Chinese, Chinese will appear The garbled code problem; we can solve the garbled code problem by customizing a function in which it traverses the Chinese string and sets the encoding format.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What functions can the php strrev function achieve?. 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