【问题标题】:How to extract specific part of string where the length of the part changes? [duplicate]如何提取部分长度发生变化的字符串的特定部分? [复制]
【发布时间】:2018-04-15 10:52:09
【问题描述】:

我试图只从这个字符串中获取第一个 19.45 ``有没有办法抓住介于两者之间的所有内容...“raw”:AND ,“fmt ...所以我只得到数字。希望有人可以帮帮我...

更新:找到了我要找的东西。
How to get a substring between two strings in PHP?

<?php 
$str = "targetMeanPrice":{"raw":19.45,"fmt":"19.45"}";

function GetBetween($var1='',$var2='',$pool){
$temp1 = strpos($pool,$var1)+strlen($var1);
$result = substr($pool,$temp1,strlen($pool));
$dd=strpos($result,$var2);
if($dd == 0){
    $dd = strlen($result);
}
return substr($result,0,$dd);
}

echo GetBetween('raw":',',"fmt', "$str" ); 
?>

输出 = 19.45

【问题讨论】:

  • 这是整个源字符串吗?它看起来像一个不完整的 JSON 块——你可以使用 json_decode() on。

标签: php html


【解决方案1】:
$decodedJSON = json_decode($yourJson);
$raw = $decodedJSON->targetMeanPrice->raw;

$raw 现在将包含 raw 的值,即 19.45

$decodedJSON = json_decode($yourJson,true);
$raw = $decodedJSON['targetMeanPrice']['raw']

source

【讨论】:

  • 关于您的“找到”答案,我认为当您实际上有一个 JSON 对象时执行字符串 pos 有点愚蠢。为什么不利用它?
【解决方案2】:

试试这个:

   <?php 

    $json = '{"targetMeanPrice":{"raw":19.45,"fmt":"19.45"}}';
    $json = json_decode($json);
    echo $json->targetMeanPrice->raw;

    ?>

【讨论】:

    【解决方案3】:

    您可以使用 strpos(...) 查找 "raw": 和第二个 strpos(..) 查找 ,"fmt,而不是通过 strpos(...) 计算返回索引的长度/差异并使用 substr(. ..) 提取期望值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多