In PHP, you can use the substr_replace() function to replace the last two characters of a string with other characters. This function can start from the specified position in the string and replace the specified number of characters with the specified value; you only need to set the second parameter of the function to the specified replacement value, the third parameter to "-2", and the fourth parameter to Just set it to 2 or omit it, the syntax is "substr_replace(string,"replacement value",-2,2)" or "substr_replace(string,"replacement value",-2)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use the substr_replace() function Replace the last two characters of the string with other characters.
The substr_replace() function can replace a substring of a specified length (a specified number of characters) with a specified value 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.
|
You only need to set the second parameter of the substr_replace() function to the specified replacement value, the third parameter to "-2", and the fourth parameter to 2 or omit it to replace the last two characters of the string with other characters.
Example: Replace the last two digits of the string "hello123" with "**"
<?php header("Content-type:text/html;charset=utf-8"); $str="hello123"; echo "原字符串:"; var_dump($str); echo "将字符串后两位替换为**:"; $newStr1=substr_replace($str,"**",-2,2); var_dump($newStr1); $newStr2=substr_replace($str,"**",-2); var_dump($newStr2); ?>
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to replace the last two characters of a string with other characters in php. For more information, please follow other related articles on the PHP Chinese website!