Home >Backend Development >PHP Problem >string php how to replace string
There are two functions in PHP that can replace strings, namely: 1. substr_replace function, which is used to replace part of a string with another string; 2. str_replace function, which Used to replace other characters in a string.
The operating environment of this article: windows7 system, PHP version 7.1, DELL G3 computer
PHP string replacement substr_replace and str_replace functions
Used to replace the specified string from a string.
Relevant functions are as follows:
substr_replace() function is used to replace part of the string with another string and return a mixed type.
Syntax:
mix substr_replace ( mixed string, string replacement, int start [, int length] )
Parameter | Description |
---|---|
string | String to be processed |
replacement | String to be inserted |
start | The starting position of the string, the starting position is 0, if it is negative, it starts from the specified position at the end of the string |
length | Optional, the length of the string returned, the default is until the end of the string, if it is negative, it will be returned from the end of the string |
Example:
<?php echo substr_replace('abcdef', '###', 1); //输出 a### echo substr_replace('abcdef', '###', 1, 2); //输出 a###def echo substr_replace('abcdef', '###', -3, 2); //输出 abc###f echo substr_replace('abcdef', '###', 1, -2); //输出 a###ef ?>
If start is a negative number and length is less than or equal to start, length is 0.
str_replace() function uses a string to replace other characters in the string and returns a mixed type. [Recommended learning: PHP video tutorial]
Syntax:
mixed str_replace( mixed search, mixed replace, mixed string [, int &count] )
Parameter | Description |
---|---|
search | The string to be found (replaced) |
replace | String to replace search |
string | String to be processed |
count | Optional, a variable that counts substitutions |
Example:
<?php echo str_replace("world","earth","Hello world!"); //输出 Hello earth! //替换多个,且第二个参数为空字符 echo str_replace("o","","Hello world!"); //输出 Hell wrld! //使用数组 $arr = array("e", "o"); $arr2 = array("x", "y"); echo str_replace($arr, $arr2, "Hello World of PHP", $i); //输出 Hxlly Wyrld yf PHP echo $i; //输出4 ?>
The above is the detailed content of string php how to replace string. For more information, please follow other related articles on the PHP Chinese website!