php - PHP - substr() 错误或无效参数
问题描述
我在 PHP 7.0.13 版本的 PHP 项目中工作
我最近在处理 JSON,我有一个 JSON 文件需要解码为 PHP,但在解码 JSON之前,我需要清理JSON 在其中获得的文件中的一些抽象字符串,以清理substr()
用于获取 JSON的字符串.
当我写代码时,像这样:
$jsonraw = "\"{ JSON should be here, later }\"";
$cutstart = strpos($jsonraw, "{");
$cutend = strrpos($jsonraw, "\"");
$jsonclean = substr($jsonraw, $cutstart, $cutend);
echo $jsonclean;
输出是这样的
{ JSON 应该在这里,稍后 }
但是当字符串是这样的
$jsonraw = "\"some abstract string to remove { JSON should be here, later }\"";
输出变成了这样
{ JSON 应该在这里,稍后 }"
正如我们所看到"
的,在字符串的最后一个引号符号,我试图减少$cutend
, 像 this$jsonclean = substr($jsonraw, $cutstart, --$cutend);
和 this$cutend-1
任何帮助,我很感激。对不起,我的英语不好
解决方案
您可以使用preg_match
从该字符串中获取 json:
$string = "some abstract string to remove { JSON should be here, later }";
preg_match('/\{.*\}/', $string, $match);
var_dump($match[0]);
结果将是:
string(30) "{ JSON should be here, later }"
推荐阅读
- android - 为什么我会收到“Entity class must be annotated with @Entity”错误,我该如何忽略它?
- excel - 使用 Excel VBA 将字符串转换为日期
- r - 将预制的 gganimate gif 加载到 rmarkdown 块中以添加标题
- jenkins - 当我定义 BooleanParameterDefinition 时,Jenkins 的 Job DSL 抛出 ConcurrentModificationException
- json - 如何获取包含对象列表的文档?- 火库
- android - 使本机反应以使用位于其他计算机上的 Android 模拟器
- excel - 如何检查单元格是否包含特定格式的日期?
- javascript - 带有 Courtain.js 库的下一个 JS 未接收参数
- docker - 在不重复指令的情况下将相同的变量传递给 docker-compose 中的多个服务?
- vbscript - 编码vbscript转换后从文本文件中删除空白行