Home > Article > Backend Development > How to replace 1 character in php string
Method to replace one character: 1. Use the "str_replace("single character", "replacement value", string)" statement to replace the specified single character in a case-sensitive manner; 2. Use " The substr_replace(string, "replacement value", starting position, 1)" statement can replace a character starting from the specified position.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php string replacement 1-character method:
1. Use the str_replace() function
str_replace() function can replace the specified single character in a case-sensitive manner. character.
<?php header('content-type:text/html;charset=utf-8'); $str = "abCdABcD"; echo "原字符串:".$str; $replace = '-'; $search = 'b'; echo "<br>替换后:".str_replace($search, $replace, $str); ?>
Note: PHP also has a str_ireplace() function that is similar to str_replace(), but is not case-sensitive.
<?php header('content-type:text/html;charset=utf-8'); $str = "abCdABcD"; echo "原字符串:".$str; $replace = '-'; $search = 'b'; echo "<br>替换后:".str_ireplace($search, $replace, $str); ?>
2. Use substr_replace() function
substr_replace() function can replace a character starting from the specified position.
<?php header('content-type:text/html;charset=utf-8'); $str = "abCdABcD"; echo "原字符串:".$str; echo "<br>替换后:".substr_replace($str,"#",2,1); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace 1 character in php string. For more information, please follow other related articles on the PHP Chinese website!