2011-07-10 44 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