1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Introduction to Preg in PHP


4 of 5

Preg_Replace PHP Function
The preg_replace function is used to do a find-and-replace on a string or an array. We can give it one thing to find and replace (for example it seeks out the word 'him' and changes it to 'her') or we can give it a full list of things (an array) to search for, each with a corresponding replacement. It is phrased as preg_replace ( search_for, replace_with, your_data , optional_limit, optional_count ) The limit will default to -1 which is no limit. Remember your_data can be a string or an array.

 $data = "The cat likes to sit on the fence. He also likes to climb the tree."; 
 $find ="/the/"; 
 $replace ="a"; 
 //1. replace single word 
 Echo "$data <br>"; 
 Echo preg_replace ($find, $replace, $data); 
 //create arrays 
 $find2 = array ('/the/', '/cat/'); 
 $replace2 = array ('a', 'dog'); 
 //2. replace with array values 
 Echo preg_replace ($find2, $replace2, $data); 
 //3. Replace just once
 Echo preg_replace ($find2, $replace2, $data, 1); 
 //4. Keep a count of replacements 
 $count = 0; 
 Echo preg_replace ($find2, $replace2, $data, -1, $count); 
 Echo "<br>You have made $count replacements"; 
In our first example we simply replace 'the' with 'a'. As you can see these are cAse seNsiTIvE. Then we set up an array, so in our second example we are replacing both the words 'the' and 'cat'. In our third example, we set the limit to 1, so each word is only replaced one time. Finally in our 4th example, we keep count of how many replacements we have made.
Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Technology
  3. PHP / MySQL
  4. PHP Functions
  5. Introduction to Preg - the Preg_replace () PHP Function

©2014 About.com. All rights reserved.