【问题标题】:how to deep rename array keys if they don't match a regex pattern如果数组键与正则表达式模式不匹配,如何深度重命名它们
【发布时间】:2019-08-21 09:29:52
【问题描述】:

我需要将 JSON 对象转换为 XML 文档。我使用this class,它做得很好。

问题是,有时我的 JSON 对象的属性会在类中引发异常,当元素名称 (W3C) 非法时,例如此输入:

{"first":"hello","second":{"item1":"beautiful","$item2":"world"}}

标签名称中有非法字符。 tag: $item2 in node: second

触发的函数是:

/*
 * 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 之前“清理”它。

因此,我需要一个函数,在将输入数据转换为 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);

我怎么能这样做?谢谢!

【问题讨论】:

  • 不确定您想要什么,删除"$xxx":"zzz" 中的$?试试preg_replace('~(")\$(\w+":")~', '$1$2', $text)
  • @WiktorStribiżew:问题已更新
  • 我建议更改课程本身。当您拥有{"item1":"beautiful","$item1":"world"} 时,更改源数据可能会导致问题,因为这会创建两个带有item1 的项目,而这两个项目在数组中会被覆盖,并且您最终会在输出中得到一个值。

标签: php arrays regex xml


【解决方案1】:

我认为你想要的是这样的。创建一个新的空数组,递归循环遍历您的数据和过滤键。最后返回新数组。为了防止重复密钥,我们将使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多