0

I have just started to learn Regular Expressions and I think this can be done using regex, but not able to find a proper regex match. Here is the situation: I want to fill the Key in the array with the respective values, but make everything lowercase and underscore for space.

Example PHP array:

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

Output should be:

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

I was able to use strtolower() but getting stuck with using preg_replace(). Can I even do this with regex?

Thanks.

1
  • 1
    u can do this without using regex, consult string function in php manual Commented Jan 23, 2013 at 19:59

3 Answers 3

1

As slier said, it can be done without preg_replace

Here is a snippet

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

Check http://php.net/str_replace Quick introduction

str_replace(find, replace, value);

find can be an array containing common unwanted chars, such as array('-', '/', ' ', .. etc);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use preg_replace() and strtolower() to achieve this:

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

Comments

0

Confirmed working:

$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);

Reference:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.