PHP Function str_replace()

Magnifying Glass Photo by Angelo_Giordano on Pixabay

Welcome to the inaugural Function Friday post!

I created Function Friday as a way to both share my PHP and WordPress knowledge with others, and force myself to continue to learn on a schedule. After graduating with my Bachelors of Science in Technology degree in 2014, I realized I crave structure in my learning process. The purpose of this blog is to provide that structure for myself, as well as help the coding community.

So let’s get started with this week’s Function Friday! Every time I visit, I am blown away with the amount of built-in string functions. The function I’ll cover today is one that stumps me every time.

str_replace( $search, $replace, $subject )

The thing that I always mix up with str_replace is the order of the parameters. The parameters are $search, $replace, and $subject, where $search is the string you are trying to find, $replace is what you want it to be, and $subject is your old string (or array) that you’re searching through. (In my folly, my first instinct is always to put the $subject first.)
If you have trouble keeping the parameters straight, compares $search to the “needle,” and $subject to the “haystack.”

I hope you have a better understanding of the str_replace PHP function, or at least can use this post as a quick reference for your projects. Feel free to tweet at me @megabyterose with feedback and/or ideas for my next Function Friday! 🙂