views:

108

answers:

4

Array example entry:

test : title=Diet    Coke

Becomes

test:title=Diet Coke
+1  A: 

I'm not a regex guru, but this is the general idea:

$my_array = array('test : title=Diet    Coke');

function do_crazy_thing($string){
  $string = preg_replace('/  +/', ' ', $string);
  $string = preg_replace('/ : /', ':', $string);
  return $string;
}

$my_array = array_map('do_crazy_thing', $my_array);

EDIT: have just tested this and seems to work fine.

Seb
+1  A: 
foreach ( $a as $k=>$v ) {
    $v     = preg_replace("`\s*:\s*`", ":", $v);
    $a[$k] = preg_replace("`\s*`", " ", $v);
}
Justin Johnson
+5  A: 

This approach using regular expression handles just one string, but if you want to do an array, just iterate over the array and apply this to each string:

$target="test : title=Diet    Coke";
print_r(preg_replace('/\s*([\s:])\s*/','\1',$target));

Output:

test:title=Diet Coke
Mark Byers
A: 

the non regex way,

$string= "test : title=Diet    Coke";
$s = explode(":",$string);
$s[0]=trim($s[0]);
$s[1]=trim($s[1]);
print implode(":",$s);
And to compact the whitespace after the colon, replace the line $s[1]=trim($s[1]); with:$s[1] = implode(" ", array_filter(array_map("trim",explode(" ",$s[1]))));I'm in a computer lab and PHP isn't installed here, so I'm not sure if that'll actually work but hopefully you get the idea.
Roman Stolper