PHP:用下划线替换对象变量中的破折号 [英] PHP: Replace Dashes in Object Variables With Underscores
本文介绍了PHP:用下划线替换对象变量中的破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个来自外部源的 PHP 对象(使用 PEAR 的 XML_Serializer).一些变量在名称中带有破折号,例如:
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.
推荐答案
使用 get_object_vars()
并根据需要替换:
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});
}
}
}
这篇关于PHP:用下划线替换对象变量中的破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文