我有很多文字字符串,比如
'从12.34到56.78'
OR
'12 .34至56.78'
OR
'12 0.34'
我想在所有这些字符串中修改这些数字
<?php
$array = explode(' ',$string);
foreach ($array as $value) {
if(is_numeric($value))
$newarray[] = round($value); // or other functions
else
$newarray[] = $value;
}
$newstring = implode(' ',$newarray);
这是进行任何修改的最佳方式吗?
答案 0 :(得分:1)
从您的评论中,您可以查看preg_replace_callback()
考虑以下代码,可以非常轻松地对所有数字进行舍入:
<?php
$strings = array('from 12.34 to 56.78', '12.34 to 56.78', '12.34');
$values = array();
$regex = '~\b\d[\d.]+\b~';
foreach ($strings as $string) {
$string = preg_replace_callback($regex,
function($match) {
// or anything else
return round($match[0]);
},
$string);
$values[] = $string;
}
print_r($values);
# [0] => from 12 to 57
# [1] => 12 to 57
# [2] => 12
?>