php - 如果数组键与正则表达式模式不匹配,如何深度重命名它们
问题描述
我需要将 JSON 对象转换为 XML 文档。我使用这个可以很好地完成工作的类。
问题是,有时我的 JSON 对象的属性会在类中引发异常,当元素名称 (W3C) 非法时,例如此输入:
{"first":"hello","second":{"item1":"beautiful","$item2":"world"}}
标签名称中有非法字符。标签:$item2 在节点:第二
触发的功能是:
/*
* Check if the tag name or attribute name contains illegal characters
* Ref: http://www.w3.org/TR/xml/#sec-common-syn
*/
private static function isValidTagName($tag){
$pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
}
然后我想做的是在将 JSON 输入转换为 XML 之前“清理”我的 JSON 输入。
因此,我需要一个函数在将输入数据转换为 XML 之前对其进行重新格式化。
function clean_array_input($data){
//recursively clean array keys so they are only allowed chars
}
$data = json_decode($json, true);
$data = clean_array_input($data);
$dom = WPSSTMAPI_Array2XML::createXML($data,'root','element');
$xml = $dom->saveXML($dom);
我怎么能那样做?谢谢 !
解决方案
我想你想要的是这样的。创建一个新的空数组,递归循环遍历您的数据和过滤器键。最后返回新数组。为了防止重复密钥,我们将使用 uniqid。
function clean_array_input($data){
$cleanData = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = clean_array_input($value);
}
$key = preg_replace("/[^a-zA-Z0-9]+/", "", $key);
if (isset($cleanData[$key])) {
$key = $key.uniqid();
}
$cleanData[$key] = $value;
}
return $cleanData;
}