Home >Backend Development >PHP Problem >How to replace the last few digits of a string in php
In PHP, you can use the substr_replace() function to replace the last few characters of a string. You only need to set the third parameter of the function to a negative value. The syntax is "substr_replace (string, Replacement value, -N)" will replace all remaining characters starting from the Nth character from the last in the string, that is, replace the last N characters of the string.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the substr_replace() function to replace the last few characters of the string.
The substr_replace() function can replace the specified number of characters starting from the specified position in the string.
substr_replace(string,replacement,start,length)
Parameters | Description |
---|---|
string | Required . Specifies the string to check. |
replacement | Required. Specifies the string to be inserted. |
start | Required. Specifies where in the string to begin replacement.
|
length | Optional. Specifies how many characters to replace. The default is the same as the string length.
|
substr_replace() Replaces the substring qualified by the start and optional length parameters in a copy of string string using replacement.
If start is a positive number, replacement will start from the start position of string. If start is negative, the replacement will start at the start position from the bottom of string.
If the length parameter is set and is a positive number, it represents the length of the replaced substring in string. If set to a negative number, it represents the number of characters from the end of the substring to be replaced from the end of string. If this parameter is not provided, the default is strlen(string) (the length of the string). Of course, if length is 0, then the function of this function is to insert replacement at the start position of string.
Example:
<?php header('content-type:text/html;charset=utf-8'); $str = 'hello world!'; echo "原字符串:".$str."<br><br>"; $replace = 'AA'; echo "替换后2位字符:".substr_replace($str, $replace,-2)."<br>"; echo "替换后3位字符:".substr_replace($str, $replace,-3)."<br>"; echo "替换后4位字符:".substr_replace($str, $replace,-4)."<br>"; echo "替换后5位字符:".substr_replace($str, $replace,-5)."<br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace the last few digits of a string in php. For more information, please follow other related articles on the PHP Chinese website!