PHP: Replace First Occurance Only

» »

Have you ever wanted to replace a word in a text string, but not all occurances but only the first or last? Here's a script that will do just that.

For one of my web projects — more specifically, this exact website — I needed to be able to replace the first and last occurance of a word in a text string.

Fortunately, doing this in PHP does not require regular expression or anything of the kind. This is good of two reasons;

  1. I am really, really bad at regular expressions
  2. They can be a real performance hog

So, not only was this easier to do than I thought, it's also done with better performance than I thought.

Replace first or last occurance

So let's get to the script itself. It's rather straightforward, as it simply looks up the position of the string you want to replace and replaces from that position + the length of the source word.

Here it is:

function str_replace_first($from,$to,$string,$reverse) {
  if ($reverse==1) { $position = strrpos($string,$from); }
  else { $position = strpos($string,$from); }
  if ($position!==false) {
    return substr_replace($string,$to,$position,strlen($from));
  }
}

As you can see, the inputs are the following:

  • from = what you need to replace from
  • to = what you need to replace to
  • string = your source string
  • reverse = if you want to replace the first occurance from the end of the string

I sincerely hope this has helped you out in your own projects.