Replace several keywords in a string at the same time. It’s really complicated. It should be done with strtr. At that time, I only focused on str_replace. I thought there was no other way and I could ignore this code.
- function replace($string,$keyArray,$replacement,$i){
- $result='';
- if($i<(count($keyArray))){
- $strSegArray=explode($keyArray [$i],$string);
- foreach ($strSegArray as $index=>$strSeg){
- $x=$i+1;
- if($index==(count($strSegArray)-1))
- $result=$result.replace($strSeg,$keyArray,$replacement,$x);
- else
- $result=$result.replace($strSeg,$keyArray,$replacement,$x).$replacement[$ i];
- }
- return $result;
- }
- else{
- return $string;
- }
- }
-
- $string=' The key name array can contain both integer and string type key names, 12345678 because PHP does not actually Distinguish between indexed arrays and associative arrays.
- If no key name is specified for the given value, the current largest integer index value will be taken, and the new key name will be that value plus one. If the specified key name already has a value, the value will be overwritten. ';
-
- $keyArray=array('array','integer','2345','key name');
- $replacement=array('AAAA','BBBB','CCCC','DDDD');
-
- echo replace($string,$keyArray,$replacement,0);
Copy code
|