首页 > 解决方案 > 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

任何帮助,我很感激。对不起,我的英语不好

标签: phpjsonstringsubstr

解决方案


您可以使用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 }"

推荐阅读