Alisol – Web Design and Digital Marketing Agency

PHP str_replace() Function

The str_replace() function takes three parameters:

  • The string is to be replaced.
  • The line to replace it with.
  • The location in the row where the replacement should occur.

The first two are pretty self-explanatory, but let’s look at the third parameter.

The third parameter is a bit more complex. It’s an array of integers that represent the start and end position of the substring that should be replaced. So, if you wanted to replace all instances of “hello” with “goodbye,” you would use the following code:

str_replace(“hello”, “goodbye”, array(0, 5));

This would replace the first instance of “hello” with “goodbye” that occurs in the string, and it would replace the fifth instance of “hello” with “goodbye.” You can also use negative numbers to indicate positions from the end of the string. So, if you wanted to replace the last instance of “hello” with “goodbye,” you would use this code:

str_replace(“hello”, “goodbye”, array(-1));

This would replace the last instance of “hello” with “goodbye.” Pretty nifty, huh?

There are a few other parameters that are supported by the str_replace() function, but they’re beyond the scope of this tutorial. If you would like to learn more about them, check out the official documentation here: http://php.net/manual/en/function.str-replace.php#85904

Now that we’ve covered how it works, let’s take a look at some other common usages for str_replace(). For example, if you wanted to remove all HTML tags from a string, you could use the following code:

str_replace(“<p>”, ” “, $html);

This would replace all instances of “<p>” with nothing (by default, there is no location specified, so it replaces every instance). Similarly, if you wanted to remove all instances of any other HTML tag, you could specify the location as follows:

str_replace(“<p>”, ” “, $html, 2);

This would replace every instance of “<p>” with nothing but would leave everything before and after untouched. Awesome!

Now it’s your turn to give this a try. Make sure you share what you came up with within the comment section below so we can check it out. Have fun!

That wraps up today’s tutorial on how to use str_replace(); feel free to post your results in the comments below if you come up with anything neat or just want to show off that you’ve actually used this function before. See you next time!

Leave a Comment

Quick Talking, Start Doing!

Subscribe

Nulla consequat malesuada turpis, fringilla varius ipsum.