如何从Php中的String获取子字符串

时间:2016-02-13 07:11:37

标签: php

我有一个像

这样的字符串
$totalValues ="4565:4,4566:5,4567:6";

现在我只希望':'之后的值以逗号分隔,即我想要像$SubValues = "4,5,6"这样的字符串

谢谢

3 个答案:

答案 0 :(得分:2)

使用array_mapimplodeexplode

$totalValues ="4565:4,4566:5,4567:6";

echo implode(',',array_map(function($val){
    $val = explode(':',$val);
    return $val[1];
},explode(',',$totalValues)));

答案 1 :(得分:2)

  

尝试使用此代码

   <?php
    $str="4565:4,4566:5,4567:6";;
    $data =explode(",", $str);
    echo '<pre>';
    print_r($data);
    $newstring="";
    foreach ($data as $key => $value) {
        preg_match('/:(.*)/',$value,$matches);
        $newstring.=$matches[1].",";

    }
    echo rtrim($newstring,",");

输出 o/p image

我已更新我的代码,请检查

<?php
    $str="4565:4,4566:5,4567:6";
    $data1=explode(",", $str);
    $newstring1="";
    foreach ($data1 as $key1 => $value) {
        preg_match('/(.*?):/',$value,$matches);
        $newstring1.=$matches[1].",";

    }
    echo rtrim($newstring1,",");

O/P

答案 2 :(得分:0)

你可能会这样想:

$totalValues ="4565:4,4566:5,4567:6";
$temp = explode(':', $totalValues); 
$subValues = $temp[1][0];
$x = count($temp);
for ($i = 2; $i < $x; $i++) {
    $subValues .= ',' . $temp[$i][0];
}
echo $subValues;