Fri, 17 May 2024


Str_Replace PHP Function

By: Anton, NetArt Media
Wed, 1 August 2018
Str_Replace PHP Function

During my time as a PHP web developer I have come across numerous scripts that needed to be updated and/or completely re-written, for any number of reasons. I don't think I've ever seen one that didn't include the str_replace function. This is how commonly used it is, and for very good reason.

Str_replace literally replaces parts of a string. By simply entering in the part of the string we want to change in the first parameter and then what we would like to replace it with in the second, we get our desired result. Here's our first example below.


Here we have a small array of Twitter profile urls. Say they came from a database or a file they were saved into at one time. Or even perhaps coming from a remote location somewhere on the net. Whichever, our goal here is to create the well-known Twitter profile anchor (i.e. - @twitter) from the array of urls.

Make note of my use of the str_replace function not once, but twice in the foreach statement. Some folks may think this a bit redundant. However, the alternative would have been possibly 2 foreach statements, as well as the use of implode and explode to get the array of urls. Why bother when you can simply reverse the original str_replace statement and end up with the exact same result? The result, in this case, being...

@jeff
@jane
@jack



Above is a pretty cool way to use the str_replace function, where I incorporate the strpos function into a conditional statement in order to look for an underscore, replace it with an empty space and then use the str_replace function again, along with strtolower, to create a web page url.

Here's the result of the above code block...

str-replace-function.php

Using shortcuts in your code is never a bad thing, as long as you learn to do it correctly. The last strtolower and str_replace function saved a bit of coding time, as well as helped in adding even more lines into the script than may be necessary. Remember, the more code in your scripts or pages, the longer they take to process or load.

The str_replace function is a lot of fun, I find, and offers much in the form of availability when scripting with PHP. I will be covering the strpos function in the near future. Now there is a function that can be very powerful.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox