replace a sequence of brackets with data from an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

replace a sequence of brackets with data from an array

Post 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
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

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

Post 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.
Post Reply