我有这些卷变量名。在将它们呈现给用户之前,需要对它们进行“修饰”。
$unit[] = 'cm3';
$unit[] = 'barrel_petrolium';
$unit[] = 'register_tons';
$unit[] = 'ocean_tons';
$unit[] = 'gal_us';
$unit[] = 'gal_uk';
我对前两条规则没有任何问题。我怎样才能应用第3条规则?
# replacements
$search = array('3', '_');
$replace = array('³', ' ');
# units
$temp = str_replace($search, $replace, $unit); //1st and 2nd rules
$formatted[] = $temp;
print_r($formatted);
结果将是:
cm³
barrel petrolium
register tons
ocean tons
gal us
gal uk
应该是:
cm³
barrel petrolium
register tons
ocean tons
gal (US)
gal (UK)
有什么想法吗?的谢谢!
答案 0 :(得分:4)
您可以使用preg_replace_callback:
$unit[] = 'cm3';
$unit[] = 'barrel_petrolium';
$unit[] = 'register_tons';
$unit[] = 'ocean_tons';
$unit[] = 'gal_us';
$unit[] = 'gal_uk';
$result = array_map(function ($item) {
$item = preg_replace_callback('~_\K[a-z]{2}\z~', function ($m) {
return '(' . strtoupper($m[0]) . ')';
}, $item);
return strtr($item, array('3' => '³', '_' => ' '));
}, $unit);
print_r($result);
模式细节:
~ # pattern delimiter
_ # literal _
\K # keep out all on the left (the underscore here)
[a-z]{2} # two lowercase letters
\z # anchor for the end of the string
~ # delimiter
使用\K
功能,只会替换末尾的两个字母。替换下划线是strtr()
的工作(字符翻译功能和更多)