Home » Tutorials » PHP » String Replace

String Replace

Now we arrive in the string replace tutorial of PHP.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. Let’s fight our way through an example.
$myString = "The meerkat clan was victorious.";
echo str_replace("meerkat","squirrel",$myString);
ResultThe squirrel clan was victorious.
Wow! We just changed the result of the war with a simple PHP string 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.

Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "String Replace". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/php/string-replace/.

  • Stewart, Suzy. "String Replace". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/php/string-replace/. Accessed 16 March, 2024.

  • Stewart, Suzy. String Replace. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/php/string-replace/.

0 thoughts on “String Replace”

Leave a Comment

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