I have these volume variable names. Before presenting them to the users, they need to be "retouched".
$unit[] = 'cm3';
$unit[] = 'barrel_petrolium';
$unit[] = 'register_tons';
$unit[] = 'ocean_tons';
$unit[] = 'gal_us';
$unit[] = 'gal_uk';
I have no problems for the first 2 rules. How can I also apply the 3rd rule?
# replacements
$search = array('3', '_');
$replace = array('³', ' ');
# units
$temp = str_replace($search, $replace, $unit); //1st and 2nd rules
$formatted[] = $temp;
print_r($formatted);
The result would be:
cm³
barrel petrolium
register tons
ocean tons
gal us
gal uk
It should be:
cm³
barrel petrolium
register tons
ocean tons
gal (US)
gal (UK)
Any ideas? Thanks!
You can use 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 details:
~ # 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
With the \K
feature, only the two letters at the end will be replaced. The replacement of the underscore is the job of strtr()
(a character translation function and more)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다