Search code examples
phparraysstr-replacesubstr

how to do multiple sub string replace at same time


I want to do multiple sub string replace based on starting and length. Currently I have an array with values

(user-id,replace-name,starting,length)

my string: "Hi Rameez plz call charlie"

sample array : array('123','Rameez Rami',4,6),  array('124','Charlie Russet',20,7)

And what I want is

Rameez to Rameez charlie to Charlie

my current code is

$linkAddedDescription=Input::get('description');
            foreach ($descriptionMapArray as $key=> $taggedItem) {
            //print_r($taggedItem);die;
                $tagWordStarting=$taggedItem[0];
                $tagWordLength=$taggedItem[1];
                $taggedItemData=$taggedItem[3];
                $descriptionTagLink='<a href="'.URL::to("/").'/user/profile/'.$taggedItemData->id.'">'.$taggedItemData->name.'</a>';

                $linkAddedDescription=substr_replace($linkAddedDescription,$descriptionTagLink,$tagWordStarting,$tagWordLength); 
              //break;
            }
            print_r($linkAddedDescription);die;   

Solution

  • $descriptionMapArray=json_decode(Input::get('ideaTagDescriptionMap'));
            $str=Input::get('description');
            $startofsub=0;
            $taggedDescription='';
            foreach ($descriptionMapArray as $key=> $taggedItem) {
                $tagWordStarting=$taggedItem[0];
                $tagWordLength=$taggedItem[1];
                $taggedItemData=$taggedItem[3];
                $descriptionTagLink='<a href="/user/profile/'.$taggedItemData->id.'">'.$taggedItemData->name.'</a>';
    
                $tolen=($tagWordStarting+$tagWordLength);
                $to=$tolen-$tagWordStarting;
                $v=$tolen-$startofsub;
                $sbstr=substr($str,$startofsub,$v);
                $sbstr=substr_replace($sbstr,$descriptionTagLink,($tagWordStarting-$startofsub),$tagWordLength);
                $taggedDescription.=$sbstr;
                $startofsub=$tagWordStarting+$tagWordLength;
            }    
            if($startofsub < strlen(Input::get('description'))){
                $lst_part=strlen(Input::get('description'))-$startofsub;
                $taggedDescription.=substr($str,$startofsub,$lst_part);
            }
            echo '<br/>RESULT:-'.$taggedDescription;
            die;