Swapping two parts of a line of a string

Discussion in 'PHP' started by tin2mon, Sep 16, 2010.

  1. #1
    I have a list like this stored in a single string:

    x|y
    x|y
    x|y
    x|y

    What I want PHP to do is swap the x and y over in each line so it'd look like this:

    y|x
    y|x
    y|x
    y|x

    Any ideas?
     
    tin2mon, Sep 16, 2010 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    
    <?php
    
    $string  = "x|y";
    $parts = explode("|", $string);
    echo $parts[1],"|",$parts[0]; // out-put y|x
    
     ?>
    
    PHP:
     
    MyVodaFone, Sep 16, 2010 IP
  3. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #3
    $str = preg_replace('#(.+?)\|(.+?)#', '$2|$1', $str);
    PHP:
     
    danx10, Sep 16, 2010 IP