【问题标题】:Preg_Replace for a big int fitting a certain patternPreg_Replace 用于适合特定模式的大 int
【发布时间】:2012-11-25 10:28:38
【问题描述】:

在一个巨大的字符串中,我试图清理成 json。我遇到这样的事情会破坏脚本(通常来自同一来源多次)

{
 29646191: [bunchofjson]
}

有没有我可以做的 preg_replace 来替换所有出现的

{
 stringofrandomlysizednumbers: [anything]
}

{
 "string...numbers": [anything]
}

没用的东西列表:

$output = preg_replace('/([^\\\])":([0-9]{10,})(,|})/', '$1":"$2"$3', $output);
$output = preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $output);
$output = preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $output);
$output = preg_replace('/(\d+):/', '"$1":', $output);
$output = preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $output);
$output = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $output);
$output = json_decode($output, true, 512, JSON_BIGINT_AS_STRING));

(在理想情况下,我将 json 解码为关联数组)

【问题讨论】:

  • 你能从你的数据中给出一些实际的例子吗?
  • 您的原始示例似乎是完全有效的 JSON。也许您应该使用更好的(或简单的标准)JSON 解析器?当它中断时它会给你什么错误信息?
  • 你在“没用的事情清单”中的第四次尝试对我有用。
  • @mvp 好像用的是json_decode(),没有比这更标准的了。

标签: php regex json


【解决方案1】:

我在猜测,还没有检查我的代码,但试试这个。

$output = preg_replace('/^\s*[0-9]{10,}.*/', '"string...numbers": \[anything\]', $output);

(我不确定 \[ 和 \] 是必需的。我不认为它们是必需的,但我把它们放在那里只是封装...... preg_replace 将替换任何包含任意数量空格的行,然后是 10 个连续的数字字符。

输入是这样的吗?

{
 29646191: [bunchofjson]
}

输出会是这样的

{
 "string...numbers": [anything]
}

【讨论】:

  • 我想你错过了,我需要更多的 { "29646191": [bunchofjson] }
【解决方案2】:

我相信您正在寻找这个替代品:

$output = preg_replace('/(?<=\s)(\d+)(?=\s*:)/', '"$1"', $output);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    相关资源
    最近更新 更多