2

I'm attempting to concatenate two values from a serialized array. I have this working well. The problem is one of the values Size in this case, contains white-space. I need to remove this whitespace. I have used preg_match before to remove the white-space from a variable/string. The problem I have here is how I might implement preg_match in this instance, if it is the correct approach.

foreach($contents as $item)
{
    $save = array();                
    $item = unserialize($item);
    **$item['sku'] = $item['sku'] . '' . $item['options']['Size'];** 
    //echo '<pre>';
    //print_r($item['sku']);
    //exit();
    $save['contents']    = serialize($item);
    $save['product_id'] = $item['id'];
    $save['quantity']    = $item['quantity'];
    $save['order_id']    = $id;
    $this->db->insert('order_items', $save);
}

Many thanks.

Andrew
  • 2,810
  • 4
  • 18
  • 32
Liam Fell
  • 1,308
  • 3
  • 21
  • 39
  • 1
    it's just a variable. if you could use regexes before, why can't you now? just because it's a part of an array doesn't change how you use the regexes. – Marc B Nov 06 '15 at 14:46

2 Answers2

4

PHP has function named trim() that allows trimming strings.

Smar
  • 8,109
  • 3
  • 36
  • 48
  • 2
    Useless if the whitespace is not at either end of the string. (`foo bar`) – HPierce Nov 06 '15 at 14:51
  • 1
    @HPierce Sure, I did not think about that case. I guess we’d need to ask for the actual data that is not working properly then... :) In case it’s only in either (or both) ends of the string, `trim()` should be better/faster. – Smar Nov 06 '15 at 14:52
1

You can simply use str_replace like this:

$item['sku'] .=  ' ' . str_replace(' ', '', $item['options']['Size']);
Pablo Digiani
  • 602
  • 5
  • 9