I need to perform many str_replace($search, $replace, $input)
using the same $search
and $replace
. These are exploded in a function:
function sr($input) {
$search = explode(",","s1,s2,s3,....");
$replace = explode(",","r1,r2,r3,...");
return str_replace($search, $replace, $input);
}
It is not very efficient. From another SO question, I see that I could create constant arrays, but the suggested method implies serialization. I bet this is not efficient too, but am I right?
I have a compiled language mindset, so whenever I can make something constant, I am happy. But does it make sense in PHP? I am not a PHP pro.
More precisely, knowing that this function is going to be used when users make web requests to a page, how can I optimize explodes efficiently? Is there any such thing as precompiled code in PHP? Or can I define constant arrays once for all, efficiently (like testing whether the constant is already created/available in the context)?
UPDATE
Taking Truth's suggestion into account, we can modify the function as following:
function sr($input) {
$search = array("s1","s2","s3",....");
$replace = array("r1","r2","r3",...");
return str_replace($search, $replace, $input);
}
The remaining question is: is it optimal to declare these arrays at each call or could should we try to create them as constants in the context?