Home >Backend Development >PHP Tutorial >Detailed explanation of how to use str_replace to replace multi-dimensional arrays in PHP
This article mainly introduces the implementation method of PHP using str_replace to replace multi-dimensional arrays. It combines specific examples to compare and analyze the implementation skills and precautions related to PHP's traversal and replacement operations for multi-dimensional arrays. Friends in need can refer to the following
In PHP, if you use str_replace to replace strings in an array, you can only replace a one-dimensional array. If it is a multi-dimensional array, you cannot replace all strings. So I wrote a method to realize the replacement of multi-dimensional array strings.
First, let’s test the replacement of arrays by directly using str_replace
$a = array( 'a' => 'bdc#', 'ceshi' => array('c'=>array('f'=>'#')) ); $a = str_replace('#', 'ccc', $a); var_dump($a);
The output is found as follows:
array (size=2) 'a' => string 'bdcccc' (length=6) 'ceshi' => array (size=1) 'c' => array (size=1) 'f' => string '#' (length=1)
It is found that only the strings in the one-dimensional array are replaced, and arrays with more dimensions are not replaced.
Function implements string replacement of multi-dimensional arrays
$a = array( 'a' => 'bdc#', 'ceshi' => array('c'=>array('f'=>'#')) ); function strReplace(&$array) { $array = str_replace('#', 'ccc', $array); if (is_array($array)) { foreach ($array as $key => $val) { if (is_array($val)) { strReplace($array[$key]); } } } } strReplace($a); var_dump($a);
The output is as follows:
array (size=2) 'a' => string 'bdcccc' (length=6) 'ceshi' => array (size=1) 'c' => array (size=1) 'f' => string 'ccc' (length=3)
Found that string replacement for multi-dimensional arrays is implemented
The function strReplace passes in the address of the array and replaces the string recursively. Of course, this is just a very simple method, there are many ways to implement it, just like it!
str_replace Summary of function definitions and usage
pushState and replaceState usage steps detailed explanation
Four common ways for php to read text files and the meaning of uncommon parameters in str_replace
replaceDetailed explanation of function usage
##
The above is the detailed content of Detailed explanation of how to use str_replace to replace multi-dimensional arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!