Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Kal
    Kal is offline
    Regular Coder
    Join Date
    Dec 2005
    Posts
    309
    Thanks
    0
    Thanked 0 Times in 0 Posts

    substr replace problem

    Hi guys

    if i have a string say of 11 characters, how can i display only the last 3 but replace the first 8 with an asterix.

    for example

    original 12345678910

    new ********910

    thanks in advance

  • #2
    New Coder
    Join Date
    Mar 2007
    Posts
    76
    Thanks
    0
    Thanked 0 Times in 0 Posts
    get the string lenght, and then put together the number of * you need and the rest of the string. Like:

    PHP Code:
    $length strlen($string); //get string lenght
    $newstring ""//declare a new string
    for($i=0i<$length-3$i++) //add the *'s depending on the number of characters you want to keep at the end
      
    $newstring += "*";
    $newstring += substr($string$length-3); //add the end of the string to the new one 
    echo $newstring//show the new string 
    I think that should help, I haven't tested so I might've gone wrong somewhere, but normally this should work.

  • #3
    Senior Coder rafiki's Avatar
    Join Date
    Aug 2006
    Location
    Floating around somewhere...
    Posts
    2,039
    Thanks
    19
    Thanked 42 Times in 42 Posts
    believe you left out something
    the $ before i<$length-3
    PHP Code:
    for($i=0$i<$length-3$i++) //add the *'s depending on the number of characters you want to keep at the end 

  • #4
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    PHP Code:
    $string='12345678';
    echo 
    str_repeat('*',8).substr($string,-4); 
    is a bit shorter...
    My thoughts on some things: http://codemeetsmusic.com
    And my scrapbook of cool things: http://gjones.tumblr.com

  • #5
    Senior Coder
    Join Date
    Aug 2003
    Location
    One step ahead of you.
    Posts
    2,815
    Thanks
    0
    Thanked 3 Times in 3 Posts
    PHP Code:
    $str 'your string';
    $length strlen($str);
    str_pad(substr($str, -4), $length'*'STR_PAD_LEFT); 
    I'm not sure if this was any help, but I hope it didn't make you stupider.

    Experience is something you get just after you really need it.
    PHP Installation Guide Feedback welcome.

  • #6
    Kal
    Kal is offline
    Regular Coder
    Join Date
    Dec 2005
    Posts
    309
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thanks guys for your help all sorted.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •