PHP: Replace Dashes in Object Variables With Underscores

object, php

Solution

Loop through them all using `get_object_vars()` and replace as required:

function replaceDashes (&$obj) {
    $vars = get_object_vars($obj);
    foreach ($vars as $key => $val) {
        if (strpos($key, "-") !== false) {
            $newKey = str_replace("-", "_", $key);
            $obj->{$newKey} = $val;
            unset($obj->{$key});
        }
    }
}

Problem

I have a PHP object coming from an outside source (using PEAR's XML_Serializer). Some variables have dashes in the name like: ``` <?php $company->{'address-one'}; ``` I just want to know what the best way to go through this object and rename the object properties with underscores replacing the dashes so I don't have to deal with the silly curlys and quotes.

Original source