Page 1 of 1

replace a sequence of brackets with data from an array

Posted: Sat Nov 29, 2008 7:09 pm
by yacahuma
I need to replace a sequence of brackets with data from an array

$array = '10,20,30';
$string = 'jhsdfjhsdfjh[]skfjskdfjsdkfjsdkfj[]kjsdfkjsdkfjsdf[]';

what i want is

jhsdfjhsdfjh[10]skfjskdfjsdkfjsdkfj[20]kjsdfkjsdkfjsdf[30]

Is there a secret function to do this. the reason I say this is because sometimes I spend time coding something php already has a function.

this is what i have and works

Code: Select all

 
$data='abcd:[efgh[]ijkl][]mnop';
$array = array(1,2,3,4);
foreach($array as $d)
{
  $pos = strpos($data,'[]');
  $data= str_replace('[]',"[$d]",substr($data,0,$pos+2)) . substr($data,$pos+2);
}
echo $data;
 

Thank you

Re: replace a sequence of brackets with data from an array

Posted: Sun Nov 30, 2008 2:51 pm
by omniuni
there's probably some fancy regex, but aside from that, if your way works, I see no reason not to use it.

That said, try putting it in a function so you can call it again later.