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 4 of 4
  1. #1
    Regular Coder
    Join Date
    Feb 2007
    Posts
    217
    Thanks
    25
    Thanked 1 Time in 1 Post

    remove number from string

    Let's say I've got a string like this:

    $string="4,5,10,3,11,12,1,2,9,8";

    which line do I need if I want to remove one of those numbers (inluding the comma behind it) for example 11?

  • #2
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    This might help.
    PHP Code:
    <?php
    // initial string
    $string="4,5,10,3,11,12,1,2,9,8";

    // we explode at the comma to put them into an array
    $arr explode(",",$string);

    // this is the value we want to find
    $val 11;

    // we get the key of that value, this could fail if there is more than one key.
    // I think it just returns the first one.
    $key array_search($val,$arr);

    // we do a print_r to see the values in the array initially
    echo '<pre>';
    print_r($arr);

    // now we remove the part of the array that contained the value we found
    unset($arr[$key]);

    // we need to reindex the array
    $arr array_values($arr);

    // now we do a print_r again to print out the new array
    print_r($arr);
    echo 
    '</pre>';

    // we can implode to create our string again.
    $string implode(",",$arr);

    // we echo out our new string.
    echo $string;
    ?>
    There might be an easier way but that is all I can think of right now.
    ||||If you are getting paid to do a job, don't ask for help on it!||||

  • #3
    Regular Coder
    Join Date
    Feb 2007
    Posts
    217
    Thanks
    25
    Thanked 1 Time in 1 Post
    Thanks for replying. That's a lot of code...
    Hope someone knows a shorter version before I'm gonna implement

  • #4
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,536
    Thanks
    45
    Thanked 259 Times in 256 Posts
    If the number is only showing up once and you know there will be a comma before it, you could use

    PHP Code:
    str_replace(',11'''$string); 
    You can also use regex.

    You do realize a part of the code provided to you above could be removed... its used to display the array as is so you can see whats going on.


  •  

    Posting Permissions

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