PHP string replace


Home - Tutorials - Basics

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

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.


str_replace 

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: 

 

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

 

str_ireplace 

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

 

preg_replace 

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: 

 

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

F1 Site Family
AJAX F1
CSS F1
Database F1
Forex F1
Flash F1
HTML F1
JavaScript F1
PhotoShop F1
PHP F1
 

 
MaxTutorial
Monthly mortgage payment calculator
WebFormGenerator
Forex mini accounts

Total time: 0.0131