使用preg_replace():
$array = array(
'AUD,ADF,1,06-01-2001,3.,3.9532',
'AUD,ADP,1,06-02-2001,99.8222,99.6682',
'AUD,ALL,1,06-01-2001,77.,75.9759',
'AUD,ALL,1,06-01-2001,78. ,75.9759'
);
// ----RegEx Pattern--- Replace Input
// \/ \/ \/ \/ \/
$new_array = preg_replace('/(\d+)\.(\s*)(?!\d)/', '$1', $array);
// ^^^ ^^ ^^^^ ^^^^
// | | | |
// Match any digits [0-9] <---| | | |
// Match a point <-------| | |
// Match spaces and make it optional<-- |
// |
// Lookahead, which means that if there <--|
// is no digits after: <--|
// digit[point][0 or several spaces] <--|
// The whole thing won't be matched. <--|
// Addition: the first (\d+) is the first match group
// That's why we used $1 in replace !
// \d -> [0-9]
// \s -> space
// \. -> points have to be escaped
// (?!) -> Lookbehind (check : http://php.net/manual/en/regexp.reference.assertions.php)
// * -> Occurs 0 time or plus
// + -> occurs 1 time or plus
// The '/' at the begin and the end are delimiters
print_r($new_array);
输出:
Array
(
[0] => AUD,ADF,1,06-01-2001,3,3.9532
[1] => AUD,ADP,1,06-02-2001,99.8222,99.6682
[2] => AUD,ALL,1,06-01-2001,77,75.9759
[3] => AUD,ALL,1,06-01-2001,78,75.9759
)
编辑:回答下面评论中的问题:
正则表达式是关于正则模式的。从所需的输出中,我可以看到您希望将除数字(整数和双精度/浮点数)之外的所有内容都放在引号中,我们还可以将日期放在引号之间。所以这是一种方法:
$new_array = preg_replace('/(\d+)\.(\s*)(?!\d)/', '$1', $array); // remove some dots & spaces
$new_array_2 = preg_replace('/([a-zA-Z]+|\d+-\d+-\d+)/', '\'$1\'', $new_array);
// Match letters <--^-^-^-^-^ ^-^-^-^-^---> Match digits-digits-digits (for the date part), I don't want to use a LOOOONG RegEx to check if it's valid ...
print_r($new_array); // First replacement
print_r($new_array_2); // Second replacement
通过使用一些 PHP-Fu,还有另一种更可靠的方法:
$new_array = preg_replace('/(\d+)\.(\s*)(?!\d)/', '$1', $array); // remove some dots & spaces
// For this code YOU NEED PHP 5.3+ since it's using anonymous functions
$new_array_2 = array_map(function($val){
$pieces = explode(',', $val);
$pieces2 = array_map(function($val2){
if(preg_match('/^\d+(\.\d+)?$/', $val2)){
return $val2;
}else{
return "'$val2'";
}
}, $pieces);
return(implode(',',$pieces2));
}, $new_array);
print_r($new_array);
print_r($new_array_2);
输出:
Array
(
[0] => AUD,ADF,1,06-01-2001,3,3.9532
[1] => AUD,ADP,1,06-02-2001,99.8222,99.6682
[2] => AUD,ALL,1,06-01-2001,77,75.9759
[3] => AUD,ALL,1,06-01-2001,78,75.9759
)
Array
(
[0] => 'AUD','ADF',1,'06-01-2001',3,3.9532
[1] => 'AUD','ADP',1,'06-02-2001',99.8222,99.6682
[2] => 'AUD','ALL',1,'06-01-2001',77,75.9759
[3] => 'AUD','ALL',1,'06-01-2001',78,75.9759
)