修改字符串PHP中的数字

时间:2011-07-10 16:44:20

标签: php

我有一个这样的字符串:

$string = "1,4|2,64|3,0|4,18|";

在逗号后访问数字的最简单方法是什么?

例如,如果我有:

$whichOne = 2;

如果whichOne等于2,那么我想将64放入一个字符串中,并为其添加一个数字,然后将其再次放回原来的位置(下一个)到2,

希望你明白!

5 个答案:

答案 0 :(得分:1)

$numbers = explode("|", $string);
foreach ($numbers as $number)
{
    $int[] = intval($number);
}

print_r($int);

答案 1 :(得分:1)

genesis'es回答修改

$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
    $numbers = explode(',',$pair);
    if ($numbers[0] == $search_for){
        //do whatever you want here
        //for example:
        $numbers[1] += 100; // 100 + 64 = 164
        $pairs[index] = implode(',',$numbers); //push them back
        break;
    }
}
$new_string = implode('|',$pairs);

答案 2 :(得分:1)

$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
    if ($v) {
        $ex = explode(',', $v);
        $values[$ex[0]] = $ex[1];
    }
}

要查找say,2的值,您可以使用$whichOne = $values[2];64

答案 3 :(得分:1)

我认为像其他人建议的那样使用foreach要好得多,但你可以像下面这样做:

$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";

echo "Starting String: $string <br>";

$pos = strpos($string, $whichOne);

//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);

$tempstring = explode("|", $valuepos);
$value = $tempstring[0];  //This will ow be 64

$newValue = $value + 18;

//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;

$string = str_replace($replaceValue, $newValue, $string);

echo "Ending String: $string";

这导致:

Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|

如果有多个索引为2,则可能会遇到问题...这只适用于第一个2的实例。

希望这有帮助!

答案 4 :(得分:1)

我知道这个问题已经回答了,但我做了一行解决方案(也许它的速度也快了):

$string = "1,4|2,64|3,0|4,18|";

$whichOne = 2;
$increment = 100;

echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);

在控制台中运行示例:

noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|

请参阅http://us.php.net/manual/en/function.preg-replace.php