Why use explode and implode in this function

I need to change some dates in login.php files weekly. On stackexchange, I found the function below.

Together with my other code, it works fine on my localhost!

I’m just wondering why this guy chose to use explode and implode instead of str_replace()
I’m a great believer in “if it ain’t broke, don’t fix it” so I don’t really want to mess with it! Also, I don’t really understand what is going on!

function replace_string_in_file($filename, $string_to_replace, $replace_with){
				 $content=file_get_contents($filename);
				 $content_chunks=explode($string_to_replace, $content);
				 $content=implode($replace_with, $content_chunks);
				 file_put_contents($filename, $content);
				 }

Well, that is a waste of time. Too much code for a one line routine. BUT, with that said, I have found that you need to separate some things in tricky ways if the data itself is complicated. Sometimes, you might want to separate the chunk of text with one character and then remove the extra spaces around each. But, he did not TRIM() them, so not sure what his reason is. It would be much much easier to just do it this way:

file_put_contents($filename, str_replace(file_get_contents($filename), $string_to_replace, $replace_with));

But, that is hard to read really! I might do it in three lines to make it easier to read. Read the file, str_replace it, put the file out.

Remember that string processing is the most resource requirements on a server. Try to keep string processing to the minimum. If you need to call this function a lot of times, I would leave it as a function, otherwise, just process it.

Lastly, " str_replace " function in PHP did not work very well before PHP4.3 or so. Maybe this function was written before 4.3 existed. That is probably the case here.

1 Like

Thanks a lot!

I think 3 lines would be easier for me to follow. I’ll try it out tonight, got other stuff to do this morning

Sponsor our Newsletter | Privacy Policy | Terms of Service