How to delete the last two characters of a string in PHP

王林
Release: 2024-03-24 21:14:01
Original
518 people have browsed it

How to delete the last two characters of a string in PHP

PHP method of deleting the two characters at the end of a string

In PHP, deleting the two characters at the end of a string can be achieved through a variety of methods. Here are some commonly used methods, along with specific code examples.

Method one: use substr function

$str = "Hello World!";
$trimmedStr = substr($str, 0, -2);
echo $trimmedStr; // 输出:Hello World
Copy after login

Method two: use mb_substr function (for multi-byte characters)

$str = "你好,世界!";
$trimmedStr = mb_substr($str, 0, mb_strlen($str) - 2);
echo $trimmedStr; // 输出:你好,世界
Copy after login

Method three: use substr_replace function

$str = "12345";
$trimmedStr = substr_replace($str, '', -2);
echo $trimmedStr; // 输出:123
Copy after login

Method 4: Use the rtrim function

$str = "abcdefg";
$trimmedStr = rtrim($str, substr($str, -2));
echo $trimmedStr; // 输出:abcde
Copy after login

The above are several commonly used PHP methods to delete the last two characters of a string. Choose the appropriate method to implement string processing according to the specific situation. Hope it helps.

The above is the detailed content of How to delete the last two characters of a string in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!