PHP - 使用正则表达式根据值更改数组键


PHP - use regex to change Array Key based on Values

我刚刚开始学习正则表达式,我认为这可以使用正则表达式来完成,但找不到合适的正则表达式匹配。情况是这样的:我想用各自的值填充数组中的 Key,但将所有内容都设置为小写并下划线表示空格。

示例 PHP 数组:

array('' => 'Red Apple',
      '' => 'Blue Sky',
      '' => 'Circle/Earth');

输出应为:

array('red_apple' => 'Red Apple',
      'blue_sky' => 'Blue Sky',
      'circle_earth' => 'Circle/Earth');

我能够使用 strtolower(),但坚持使用 preg_replace()。我甚至可以用正则表达式做到这一点吗?

谢谢。

正如 slier 所说,它可以在没有preg_replace的情况下完成

这是一个片段

$new_key = strtolower(str_replace(array(' ', '/'), '_', $value)));

检查 http://php.net/str_replace快速介绍

str_replace(查找、替换、值);

find 可以是包含常见不需要的字符的数组,例如数组('-'、'/'、''、.. 等);

您可以使用

preg_replace()strtolower()来实现此目的:

$key = strtolower(preg_replace(array('/[^a-z]+/i', '/'s/'), "_", $string));

确认工作:

$array = array(
    'Red Apple',
    'Blue Sky',
    'Circle/Earth'
);
function nice_keys($key) {
    return strtolower(str_replace(array(' ', '/'), '_', $key));
}
$clean_keys = array_map('nice_keys', $array);
$new_array = array_combine($clean_keys, $array);
print_r($new_array);

参考资料:

  • str_replace()
  • array_map()
  • array_combine()