Home  >  Article  >  Backend Development  >  How to remove the last character from variables in php

How to remove the last character from variables in php

青灯夜游
青灯夜游Original
2022-04-18 21:05:221779browse

Removal method: 1. Use the "substr(variable,0,-1)" statement to cut off the last character of the English string in reverse order; 2. Use "mb_substr(variable,0,-1, "Character encoding ")" statement can delete the last character of the Chinese string; 3. Use the "rtrim(variable, "specified character")" statement.

How to remove the last character from variables in php

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

Remove the variables in php The last character

Method 1: Use the substr() function

Use the substr() function to cut off the last character in reverse order ( This function cannot be used with Chinese characters).

substr($arr_str, 0, -1)

Example:

<?php
$num = 12345;
$str = substr($num, 0, -1) ;
echo $num;
var_dump($str);

$str = "abcdef";
echo $str;
$str = substr($str, 0, -1);
var_dump($str);

?>

How to remove the last character from variables in php

Method 2: Use mb_substr() function

mb_substr( ) function is used the same as the substr() function, just cut off the last character in reverse order; but this function can be used for Chinese characters.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$num = 12345;
$str = mb_substr($num, 0, -1) ;
echo $num;
var_dump($str);

$str = "php中文网啦啦";
echo $str;
$str = mb_substr($str, 0, -1,"utf-8");
var_dump($str);

?>

How to remove the last character from variables in php

3. Use the rtrim() function

rtrim — delete the blank characters (or other characters) at the end of the string

rtrim($arr_str, "指定字符")

Example:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$num = "1,2,3,4,5,6,";
$str = rtrim($num, ",")  ;
echo $num;
var_dump($str);

$str = "php中文网啦啦";
echo $str;
$str = rtrim($str,"啦");
var_dump($str);

?>

How to remove the last character from variables in php

Explanation: The rtrim() function will delete consecutive characters on the right.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove the last character from variables 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