how to do multiple sub string replace at same time

184 views Asked by At

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;   
2

There are 2 answers

0
Rameez Rami On BEST ANSWER
$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;
2
Peter On

I hope I am understanding your question correctly. If so: have your string ready with the spots you want to fill in in curly braces:

$outputString = 'Hi {name} plz call {othername}';
$firstPerson = array('123', 'Rameez', 4, 6);
$secondPerson = array('132', 'Charlie', 3, 8);

Then use str_replace to fill them with your data:

$outputString = str_replace('{name}', $firstPerson[1]);
$outputString = str_replace('{othername}', $secondPerson[1]);

(The string/arrays are an example of course, this depends on your data/wishes)