开发者

Given an array, how to remove the white spaces before and after a single occuring colon & and make other multiple whitespaces turn into one?

Array example entry:

test : title=Diet    Coke
开发者_如何学Go

Becomes

test:title=Diet Coke


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


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.


foreach ( $a as $k=>$v ) {
    $v     = preg_replace("`\s*:\s*`", ":", $v);
    $a[$k] = preg_replace("`\s*`", " ", $v);
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜