Batch Rename Files in *nix

Every once in a while, you may find yourself in a situation where you need to rename a whole batch of files on your Web server. In my case, I find this especially useful when someone provides me with a folder full of friendly-named files (files that contain spaces, special characters, etc.) and I want to make them a little more Web-friendly. On Linux and Unix-based computers, it’s really simple to do this from the command line. To do so, simply use a command similar to the following:

Finding and Replacing the First or Last Substring in a String

search-replace-graphicI found this image on using Google Image search.

Today, I found myself in a position where I needed to find a substring within a larger string and then replace the last occurrence of that substring. I started out using the str_ireplace function, but quickly realized there was no way to add an offset or a limit to that function. I then started searching the Internet for a solution. I came across a handful of places where someone had asked to replace the first instance of the substring, but all of the answers seemed to recommend using the preg_replace function (which allows you to set a limit).

With no good answer, I decided to set out and build my own function to do this. I have not tested the performance of this function to determine whether it’s slower or faster than using preg_replace, but I would imagine it’s probably faster (I’d love for someone to benchmark the comparison using a variety of string lengths to find out for sure, though).