如何提取部分长度变化的字符串的特定部分?

时间:2017-11-02 19:39:40

标签: php html

我正试图从这个字符串中获得第一个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

3 个答案:

答案 0 :(得分:2)

$decodedJSON = json_decode($yourJson);
$raw = $decodedJSON->targetMeanPrice->raw;

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

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

source

答案 1 :(得分:0)

试试这个:

   <?php 

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

    ?>

答案 2 :(得分:0)

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