This article mainly introduces two php string replacement functions: str_replace and substr_replace. The former is to replace needle in all haystace and return the result after replacement of haystace, the specific part of the string to be replaced by substr_replace depends on the start position and the value of the optional parameter length.
Str_replace ()
Function prototype:
Mixed str_replace (mixed needle, mixed new_needle, mixed haystace [, int & count])
The function replaces needle in all haystace with new_needle, and returns the result after replacement with haystace. The fourth optional parameter, count, contains the number of replacement operations to be performed.
Example:
| The code is as follows: |
Copy code |
<? Php
Function n2n (){
= Array ('1', '2', '3', '4', '5', '6', '7', '8', '9 ', '0 ');
= Array ("7", "8", "9", "0", "1", "2", "3", "4", "5 ", "6 ");
= Strlen ();
For (= 0; <; ++ ){
For (= 0; <10; ++)
If (= ){
= Str_replace (,,);
Break;
}
}
Return;
}
= "1234abc56 ";
Echo n2n ();
?> |
The substr_replace () function is used to find and replace a specific substring in the string at a given position. Prototype:
String substr_replace (string, string replacement, int start, int [length]);
| The code is as follows: |
Copy code |
<? Php
Echo substr_replace ("hello world", "earth", 6); // hello earth
?> |
Negative
| The code is as follows: |
Copy code |
<? Php
Substr_replace ('huevos ', 'X',-2,-2); // huevxos
Substr_replace ('huevos ', 'X',-2,-3); // huevxos
Substr_replace ('huevos ', 'X',-2,-3); // huevxos
?> |
The function uses the string replacement to replace a part of a string. The specific part depends on the start position and the value of the optional parameter length.
The start value indicates the start offset of the string to be replaced. If it is 0 or a positive value, it is the offset calculated from the start of the string. If it is a negative value, it is