Friday, 23 January 2015

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.
<?php
 $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.

0 comments:

Post a Comment