Home  >  Article  >  Backend Development  >  How to get or delete the last few characters in php

How to get or delete the last few characters in php

青灯夜游
青灯夜游Original
2022-05-05 20:50:363334browse

php can use the "substr($str,-N)" statement to get the last character. The parameter "N" specifies the number of characters to be read; to delete the last character, use "rtrim($str,"specified character" )" statement, you can also use the "substr($str,0,-N)" statement. The parameter "N" specifies the number of characters to be deleted.

How to get or delete the last few characters in php

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

php gets the last few characters

In PHP, you can use the substr() function to read the last few characters of a string.

The substr() function returns a part of a string. Just omit the third parameter of the function and set the second parameter to a negative value (-n), n specifies the last few characters you want to read

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = "123456789";
echo "原字符串:".$str."<br>";
echo "读取后1个字符:".substr($str,-1)."<br>";
echo "读取后2个字符:".substr($str,-2)."<br>";
echo "读取后3个字符:".substr($str,-3)."<br>";
?>

How to get or delete the last few characters in php

php delete the last few characters

1. Use the rtrim() function

rtrim() function can move Except whitespace characters or other predefined characters on the right side of the string.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = "123456789";
echo "原字符串:".$str."<br>";
echo "删除后1个字符:".rtrim($str,"9")."<br>";
echo "删除后2个字符:".rtrim($str,"89")."<br>";
echo "删除后3个字符:".rtrim($str,"789")."<br>";
?>

How to get or delete the last few characters in php

2. Use the substr() function

The substr() function returns a part of the string. Just set the second parameter of the function to 0, and the third parameter to a negative value (-n), where n specifies the last few characters you want to delete.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = "123456789";
echo "原字符串:".$str."<br>";
echo "删除后1个字符:".substr($str,0,-1)."<br>";
echo "删除后2个字符:".substr($str,0,-2)."<br>";
echo "删除后3个字符:".substr($str,0,-3)."<br>";
echo "删除后4个字符:".substr($str,0,-4)."<br>";
echo "删除后5个字符:".substr($str,0,-5)."<br>";
?>

How to get or delete the last few characters in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to get or delete the last few characters 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