2011-07-10 46 views
1

内修改号码我有一个这样的字符串:字符串PHP

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

这是一个逗号后访问一些最简单的方法是什么?

举例来说,如果我有:

$whichOne = 2; 

如果whichOne等于2,然后我希望把64一个字符串,并添加了一些给它,然后把它回来的地方属于(2,旁边)

希望你明白!

回答

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); 
1
$numbers = explode("|", $string); 
foreach ($numbers as $number) 
{ 
    $int[] = intval($number); 
} 

print_r($int); 
+0

如果我只想编辑一个数字,是否必须遍历整个数组?我刚刚举了一个例子,我原来的字符串要长得多。没有办法搜索例如“2”,然后在“|”之前采用以下数字? – Daniel

+0

没有。如果你要搜索2,它可能会发现12而不是 – genesis

+1

我的意思是2后用逗号“2”, – Daniel

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]; 
    } 
} 

要查找的值,例如,2,你可以使用$whichOne = $values[2];,这是64

+0

我似乎错过了你的问题的第二部分;维塔利的答案应该适合你的需求。 – drfranks3

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

希望的第一个实例这有助于工作!

+0

谢谢! substr是什么意思? – Daniel

+0

嘿丹尼尔,脚本找到2的第一个位置。哪个将返回2的起始点。因此,添加2意味着我将索引移过数字2,然后通过逗号使您的位置索引位置现在开始于所以它基本上消除了64之前的所有内容,所以当你运行爆炸时,它将成为该数组的第一个索引,所以我们可以使用$ array [0]来访问它。 希望这是有道理的...因为我不知道我明白我刚才写了什么...;) – espradley

+0

我明白了!非常感谢你! :) – Daniel

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