Removal method: 1. Use substr_replace() to delete all characters starting from position n on the right, the syntax is "substr_replace($str,"",-n)", the parameter "n" is the number of characters to be removed ;2. Use substr(), the syntax is "substr($str,0,-n)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
phpRemove the right few characters
Method 1: Use the substr_replace() function
substr_replace() function is used to replace a part of the string starting from the specified position Replaced with another string.
substr_replace(string,replacement,start,length)
When the replacement value (second parameter replacement
) is set to the empty character '', it can be used to implement the function of deleting characters.
If you want to delete the string from the right side (tail) of the string, you need to set the startc parameter to a negative value (-n) and the length parameter to n:
means to delete n characters starting from n positions on the right side of the string.
Of course, the length parameter can also be omitted, so that all characters will be deleted starting from n digits
Implementation example:
<?php header('content-type:text/html;charset=utf-8'); $str = "123456789"; echo $str . "<br>"; echo "去掉右边1个字符:".substr_replace($str,"",-1,1); echo "<br>去掉右边1个字符:".substr_replace($str,"",-1); echo "<br>去掉右边2个字符:".substr_replace($str,"",-2); echo "<br>去掉右边3个字符:".substr_replace($str,"",-3); echo "<br>去掉右边4个字符:".substr_replace($str,"",-4); echo "<br>去掉右边5个字符:".substr_replace($str,"",-5); ?>
Method 2: Use the substr() function
The substr() function can intercept a certain length of characters from a specified position in the string. This intercepted character can be called "substr" String" or "substring"
substr(string,start,length)
You only need to set the start parameter of the function to 0 and the length parameter to -n
to delete itn
character.
Implementation example:
<?php header('content-type:text/html;charset=utf-8'); $str = "123456789"; echo $str . "<br>"; echo "去掉右边1个字符:".substr($str,0,-1); echo "<br>去掉右边2个字符:".substr($str,0,-2); echo "<br>去掉右边3个字符:".substr($str,0,-3); echo "<br>去掉右边4个字符:".substr($str,0,-4); echo "<br>去掉右边5个字符:".substr($str,0,-5); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the characters on the right in php. For more information, please follow other related articles on the PHP Chinese website!