开发者

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

开发者 https://www.devze.com 2022-12-13 12:25 出处:网络
Array example entry: test : title=DietCoke 开发者_如何学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

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

精彩评论

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