2
I have a multidimensional array with some routes and need to do the conversion of some elements defined as: (alpha), (int), (id), etc. As it is an array, at the moment I use a loop to do the replace.
I thought about approaching another way without the loop, and working with string to do the general replace. First convert the array into string using serialize
, then apply replace and then return the array with unserialize
.
From the initial way 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 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 serialize, replace will be in a string a little large and then apply unserialize.
I don’t know the limits of str_replace
- is more advantageous a loop in small strings or a single replace in a large string?
It is not a question about BENCH, only knowing advantages and disadvantages of each case, where one applies better than the other.
Enter the code so you can do the tests. Only then you can have a correct answer. If you want you can do the tests with x-debug and winCacheGrind.
– Manuel Gerardo Pereira
I even thought about making a Bench, but the configs of PHP and the machine end up influencing.
– Papa Charlie
Then all the answers will be based on the personal opinion of each.
– Manuel Gerardo Pereira
Anyway if you test on the same machine, the machine is no longer a variable.
– Manuel Gerardo Pereira
Obviously it’s not based on opinion. It’s about behavior and function performance. I don’t know what limitations and advantages of using replace in a loop or large string.
– Papa Charlie
To finish. How can you know behavior and performance without testing and measuring?
– Manuel Gerardo Pereira
There is a function for every need - str_replace for one case, preg for another... and so on. Each one has advantages and disadvantages in behavior, and I don’t know. I’m waiting for someone who can say
preg_replace
is not cool with a large string, or that is more advantage than a loop with 3 Replaces.– Papa Charlie
I do not believe that it is based on opinions, someone may have already taken that test, or they may do so to respond. Anyway a snippet of code will always be welcome.
– Jorge B.