Search code examples
phpexplodeimplode

Exploding a string multiple times then Imploding it


I have been trying to explode a string twice then imploding it. Here's what I mean by exploding it twice. So I have a string

:0,0,1,0,0:0,0,0,0,0:

I want to edit the third zero and change it to one. How do I do that? I"ve tried exploding the : then exploding the , but then Idk how to implode it.

I have tried this code but I can't implode the :

$exploding = ':0,0,0,1,0,0:0,0,0,0,0:';
        $explode = explode(':', $exploding);
        $explodes = explode(',', $explode[1]);
        $explodes[$part] = $type;
        $explodes = implode(',', $explodes);

Solution

  • I added another answer specifically answering the question asked, but might I suggest a different approach that is more extensible to more complex problems? PHP allows you to access strings as arrays, with the index being the zero-based position of a character in the string.

    Code:

    $string = ':sd0,2[wsdsjds0sdfs0ksdjse00df0';
    echo $string.'<br />';
    
    $zeroCounter = 0;
    
    for ($i=0;$i<strlen($string);$i++) {
    
    
        if ($string[$i] === '0') {
    
            $zeroCounter += 1;
    
            if ($zeroCounter === 3) {
                $string[$i] = '1';
                break;
            }
    
        }
    
    }
    
    echo $string;
    

    Output:

    :sd0,2[wsdsjds0sdfs**0**ksdjse00df0
    :sd0,2[wsdsjds0sdfs**1**ksdjse00df0
    

    Let me know if you have any questions!