PHP string replace

Home - Tutorials - Basics

This tutorial shows you how PHP string replace works with code examples and detailed explanation.

Tutorial info:

Name:PHP string replace
Total steps:1

Bookmark PHP string replace

Step 1 - PHP string replace

PHP string replace


One of the most important and most frequently used string manipulation in PHP is the string replace function. You can replace all sub-strings in a string or only some of them. You can limit the replace for only a part of the main string. Besides this you can make string replace with regular expressions.

PHP has the following built in string manipulation function to replace strings:

So let's see how to use them.


This function replaces all occurrences of the search string with the replacement string.  From PHP 5 you can limit the number of replaces as well. The syntax of str_replace is the following:

mixed str_replace ( mixed $search, mixed $replace, mixed $subject [, int &$count] )

So first you need to define a string you want to replace and as second parameter you define the new string. The last mandatory parameter is the main string itself on which you want to make the replace. Here is a string replace with str_replace example: 


  1. <?php
  2. $originalString = "I like red cars, and I have a red car near my red bike.";
  4. $newString = str_replace("red","green",$originalString);
  6. echo $originalString."<br/>";
  7. echo $newString."<br/>";
  8. ?>



This function is very similar to str_replace but it is case-insensitive. 



This function performs a regular expression search and replace. The syntax is the following:

mixed preg_replace ( mixed $pattern, mixed $replacement, mixed $subject [, int $limit [, int &$count]] )

An example code: 


  1. <?php
  2. $originalString = 'September 03, 2007';
  3. $pattern = '/(\w+) (\d+), (\d+)/i';
  4. $replacement = '${1} 01,$3';
  5. echo preg_replace($pattern, $replacement, $originalString);
  6. ?>


Tags: php string replace, string replace, php string, php replace, string, replace

PHP string replace - Table of contents
Step 1 - PHP string replace

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1425