I have a multidimensional array with some routes and need to convert some elements defined as: (alpha), (int), (id), etc. . As an array, I currently use a loop to do the replace.
I thought of approaching another way without the loop, and working with string to do the general replace. First convert the array to string using serialize
, then apply replace and then return the array with unserialize
.
From the initial form I had a foreach with separate replaces, as in the example below.
foreach( $array as $line )
{
$lineA = str_replace( ',' , '&' , $lineA );
$lineB = preg_replace( array( '(int)' , '(alpha)' ) , '([0-9]+) , ([a-zA-Z]+)' , $line[0] );
}
With new approach I have serialize, unserialize and I can use a single replace.
$line = serialize( $array );
$line = str_replace( array( '(int)' , '(alpha)' , ',' ) , array( '([0-9]+)' , '([a-zA-Z]+)' , '&' , $line );
$line = unserialize( $line );
After the serialize, the replace will be in a rather large string and then I will apply unserialize.
I do not know the limits of str_replace
- is it more advantageous to loop in small strings or a single replace in a large string?
It is not a question about BENCH, just to know the advantages and disadvantages of each case, where one applies better than the other.