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

How to remove the last character from variables in php

青灯夜游
Release: 2023-03-15 18:34:02
Original
1876 people have browsed it

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)
Copy after login

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);

?>
Copy after login

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);

?>
Copy after login

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, "指定字符")
Copy after login

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);

?>
Copy after login

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!

Related labels:
php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template