PHP String Replace

Now we arrive in the PHP String Replace. Like I said earlier, we won’t be covering all of the string functions, mainly because this is more of an introductory tutorial rather than an advanced reference guide. However, if you can understand these few functions, it should be easy for you to manipulate strings using the other functions. The string replace function is extremely useful in managing strings.

PHP String Replace


Definition and Usage

The str_replace() function replaces some characters with some other characters in a string.

This function works by the following rules:

  • If the string to be searched is an array, it returns an array
  • If the string to be searched is an array, find and replace is performed with every array element
  • If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
  • If find is an array and replace is a string, the replace string will be used for every find value

Syntax

str_replace(find,replace,string,count)

Example

$myString = "The meerkat clan was victorious.";
echo str_replace("meerkat","squirrel",$myString);

Output

The squirrel clan was victorious.

Wow! We just changed the result of the war with a simple PHP String Replace Function. We tell PHP to look for all occurrences of “meerkat” and replace it with “squirrel” in our string variable $myString.

PHP runs through and does exact matches for each and every instance, which means if we had the word “meerkat” in that string a million times, PHP would replace it with the word “squirrel” a million times.

Of course, you can also use string replace as a way to delete characters or words from a string by making the second parameter “”. PHP would go through and replace the word with an empty string.

Another useful note here is that you can use the string replace function with arrays to save you time and effort of having to learn more functions.

The string replace function is cases sensitive, so if you were to search for “MEERKAT”, you wouldn’t have changed anything. Also, there is actually a forth parameters, which you can put a number in to tell PHP the number of characters or words you want to replace.

If you want to dig deeper, you should look into the preg_replace function that using regular expressions to perform the matches, but I tried to keep string replacement simple for you. That is it, you are now a master of PHP’s string replace function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.