Replace only the first specified character in a string

Discussion in 'PHP' started by Kyriakos, Feb 20, 2013.

  1. #1
    Hi,

    i have a text in a string like this:
    $mystring = "Aspect Ratio: 16:9";
    or
    $mystring = "Contrast: 5.000.000:1";
    etc...
    Code (markup):
    I want to replace only the first colon ":" inside the string and leave the others.

    how i can do this with php?

    thanks in advance.
     
    Kyriakos, Feb 20, 2013 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    <?php
     
    $mystring = "Contrast: 5.000.000:1";
     
    $mystring = preg_replace('/:/','',$mystring,1);
     
    echo $mystring; // Contrast 5.000.000:1
     
    ?>
    PHP:
     
    Last edited: Feb 21, 2013
    MyVodaFone, Feb 21, 2013 IP
  3. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #3
    faster than regex :

    
     
    $mystring = "Aspect Ratio: 16:9";
    $result = substr($mystring, strpos($mystring, ":"));
    echo trim($result);
    
    PHP:
     
    crivion, Feb 21, 2013 IP
  4. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #4
    As far as I can make out that's not what the OP wanted.
     
    MyVodaFone, Feb 21, 2013 IP
    crivion likes this.
  5. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #5
    Oops yes correct, it will only print 16:9 / 5.000.000:1 thought that's what he wanted good point. Here's the solution :

    
     
    $mystring = "Aspect Ratio: 5.000.000:1";
    echo implode("", explode(":", $mystring, 2));
    
    PHP:
     
    crivion, Feb 21, 2013 IP