preg_replace help remove duplicates ending with letter s

Discussion in 'PHP' started by scriptglue, Nov 6, 2008.

  1. #1
    Im looking for a regular expression to remove duplicates from a list that end with the letter s. Thanks in advance!

    The list BEFORE the duplicates are removed
    dog
    dogs
    Necklace
    Necklaces
    Bracelet
    Bracelets

    The list AFTER the duplicates are removed
    dog
    Necklace
    Bracelet
     
    scriptglue, Nov 6, 2008 IP
  2. Lordo

    Lordo Well-Known Member

    Messages:
    2,082
    Likes Received:
    58
    Best Answers:
    0
    Trophy Points:
    190
    #2
    I think you will need to do it on two phases:
    1. regexp:^(.*)({1})$
    2. array_unique($array);
     
    Lordo, Nov 6, 2008 IP
  3. scriptglue

    scriptglue Banned

    Messages:
    170
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That works but only if its one word. How would i change your regexp to work with the example below?

    The list BEFORE the duplicates are removed
    dog bone
    dog bones
    14k Gold Necklace
    14k Gold Necklaces
    Gift Item Bracelet
    Gift Item Bracelets

    The list AFTER the duplicates are removed
    dog bone
    14k Gold Necklace
    Gift Item Bracelet
     
    scriptglue, Nov 6, 2008 IP
  4. Lordo

    Lordo Well-Known Member

    Messages:
    2,082
    Likes Received:
    58
    Best Answers:
    0
    Trophy Points:
    190
    #4
    Add \s inside the .*
     
    Lordo, Nov 6, 2008 IP
  5. xrvel

    xrvel Notable Member

    Messages:
    918
    Likes Received:
    30
    Best Answers:
    2
    Trophy Points:
    225
    #5
    Question,

    1. what if you have only "dogs" in the list, not "dog" and "dogs".
    Do you want to replace "dogs" into "dog" too?

    2. What if there is "glass" in your list. Do you want the last "s" to be removed too :confused: ("glas")
     
    xrvel, Nov 7, 2008 IP
  6. scriptglue

    scriptglue Banned

    Messages:
    170
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #6
    No, in this case "dogs" would stay the same "dogs"
    Im not asking how to remove 's' from the end of words
     
    scriptglue, Nov 7, 2008 IP
  7. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #7
    $items = file('file.txt');
    $clean = array();
    
    foreach($items as $item)
    {
       $item = strtolower($item);
       if(empty($clean[$item]) && empty($clean["{$item}s"]) && empty($clean["{$item}es"]))
       {
          $clean[$item] = true;
       }
    }
    
    $items = array_keys($clean);
    unset($clean);
    
    print_r($items);
    Code (markup):
     
    joebert, Nov 22, 2008 IP