how to change every character in a string EXCEPT spaces to X's

Discussion in 'PHP' started by pmf123, Jan 22, 2010.

  1. #1
    Can someone tell me how to change every character in a string EXCEPT spaces to X's in PHP?

    Example:


    "123 Hello Plaza Snottingham Hants PO12 345"

    would become:

    "XXX XXX XXXX XXXXXXXXX XXXX XXXX XXX"
     
    pmf123, Jan 22, 2010 IP
  2. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    <?php
    $string = '123 Hello Plaza Snottingham Hants PO12 345';
    $regex = '/[^\s]/i';
    $result = preg_replace($regex, 'X', $string);
    echo $result;
    ?>
    
    PHP:
     
    krsix, Jan 22, 2010 IP
  3. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That will also change tabs, newlines, etc., to X's which wasn't the spec.

    $regex = '/ /';
    PHP:
    Though in real life I'd guess you want runs of spaces collapsed to a single X:

    $regex = '/ +/';
    PHP:
    Incidentally I live in Snottingham Hants. You too?
     
    SmallPotatoes, Jan 22, 2010 IP
  4. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The spec was pretty much every single character except spaces, so anything not a space should be an X I guess..
     
    krsix, Jan 22, 2010 IP