Search code examples
phpstrpos

Php change unordered variable character


I want to change a specific character. But the order isn't exact and not only the first one. Here is the variable examples:

  • 123_456_789.jpg
  • 3210_5325_aa.jpg
  • 54321-0888_555_1111.jpg

There are 1000 variables like this. I just want to change all second "_" characters. The result must be like this:

  • 123_456x789.jpg
  • 3210_5325xaa.jpg
  • 54321-0888_555x1111.jpg

I've tried substr and str_replace but I couldn't understand how to do.
Can someone please show me a way to achieve this :)


Solution

  • If the second one is always the last one, you can use strrpos.

    <?php
    
    $vals = [
        '123_456_789.jpg',
        '3210_5325_aa.jpg',
        '54321-0888_555_1111.jpg'
    ];
    
    foreach ($vals as $val) {
        $pos = strrpos($val, '_');
        echo substr($val, 0, $pos) . 'x' . substr($val, $pos + 1) . '<BR>';
    }
    
    // 123_456x789.jpg
    // 3210_5325xaa.jpg
    // 54321-0888_555x1111.jpg
    

    If it should be really the second one occurence (independently of real number of occurences), it could be:

    <?php
    
    $vals = [
        '123_456_789.jpg',
        '3210_5325_aa.jpg',
        '54321-0888_555_1111_32.jpg'
    ];
    
    foreach ($vals as $val) {
        $pos = strpos($val, '_'); // 1st '_'
        $pos2 = strpos($val, '_', $pos + 1); // 2nd '_'
        echo substr($val, 0, $pos2) . 'x' . substr($val, $pos2 + 1) . '<BR>';
    }
    
    // 123_456x789.jpg
    // 3210_5325xaa.jpg
    // 54321-0888_555x1111_32.jpg
    

    The second variant is regex, of course. I've showed you strpos/strrpos variants due to the question.