以编程方式替换值' PHP数组中的演示文稿

时间:2014-09-15 00:13:06

标签: php preg-replace str-replace

我有这些卷变量名。在将它们呈现给用户之前,需要对它们进行“修饰”。

$unit[] = 'cm3';
$unit[] = 'barrel_petrolium';
$unit[] = 'register_tons';
$unit[] = 'ocean_tons';
$unit[] = 'gal_us';
$unit[] = 'gal_uk';
  1. 3 需要转换为³
  2. _ 需要转换为一个空格
  3. 当最后有 _xx 时,需要将其转换为(XX)
  4. 我对前两条规则没有任何问题。我怎样才能应用第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)
    

    有什么想法吗?的谢谢!

1 个答案:

答案 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()的工作(字符翻译功能和更多