Hi Guys,
Sometimes we need to replace some occurrences of string like, replace 2,3 occurrences of given string, then it creates a problem for us to manage that and to replace that particular occurrences.
To solve this problem I have made a function named "str_rep", which replaces the string occurrences at our given position. Here is that function
str_rep($search,$replace,$occurance,$string)
1. $search-> The string which will going to replace
2. $replace-> new string which will replace the search string. This parameter takes two types of values
a. Array, for example $rep=array("ravi","sunil");
b. String: this can be written in two manners
i. Comma Separated: $rep="ravi,sunil";
ii. Simple Value: $rep="ravi";
3. $occurance-> at what occurance we want to replace that certain string. This parameter takes three types of values
a. Array, for example $occ=array("1","2");
b. Integer, for example $occ1=2;
c. String: this can be written in two manners
i. Comma Separated: $occ2="1,2";
ii. Simple Value: $occ3="1";
4. $string-> The string that is going to manipulate.
NOTE: if length of replace array and occurrence array wont be same then it will replace the last found string with that occurrences. Means length(occurance)>length($replace).
The Code for this function is as follows:
//Author Ravi Kumar (+91-9351264743)
class str_rep
{
function str_rep($search,$replace,$occurance,$string)
{
$finalstr="";
$list=explode($search,$string);
if(is_string($replace))
$replace=explode(",",$replace);
if(is_string($occurance))
$occurance=explode(",",$occurance);
if(is_array($occurance)||is_string($occurance))
{
$i=0;
$replace_new="";
while($i<count($occurance))
{
if(isset($replace[$i]))
$replace_new=$replace[$i];
$list[$occurance[$i]-1].=$replace_new;
$i++;
}
$i=0;
while($i<count($list))
{
if($i==$occurance[$i]-1)
$finalstr.=$list[$i];
else
$finalstr.=$list[$i].$search;
$i++;
}
}
else
{
$list[$occurance-1].=$replace;
$i=0;
while($i<count($list))
{
if($i==$occurance-1)
$finalstr.=$list[$i];
else
$finalstr.=$list[$i].$search;
$i++;
}
}
return $finalstr;
}
}
example
$strrep=new str_rep;
$occ=array("1","2");
$occ1=array("ravi","sunil123");
echo $strrep->str_rep("<br />",$occ1,$occ,$desc);