内修改号码我有一个这样的字符串:字符串PHP
$string = "1,4|2,64|3,0|4,18|";
这是一个逗号后访问一些最简单的方法是什么?
举例来说,如果我有:
$whichOne = 2;
如果whichOne
等于2
,然后我希望把64
一个字符串,并添加了一些给它,然后把它回来的地方属于(2,
旁边)
希望你明白!
内修改号码我有一个这样的字符串:字符串PHP
$string = "1,4|2,64|3,0|4,18|";
这是一个逗号后访问一些最简单的方法是什么?
举例来说,如果我有:
$whichOne = 2;
如果whichOne
等于2
,然后我希望把64
一个字符串,并添加了一些给它,然后把它回来的地方属于(2,
旁边)
希望你明白!
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);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$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
我似乎错过了你的问题的第二部分;维塔利的答案应该适合你的需求。 – drfranks3
我认为这是更好像其他人所建议的那样使用这个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
希望的第一个实例这有助于工作!
我知道这个问题已经回答了,但我做了一个在线解决方案(也许它的速度更快,太):
$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|
如果我只想编辑一个数字,是否必须遍历整个数组?我刚刚举了一个例子,我原来的字符串要长得多。没有办法搜索例如“2”,然后在“|”之前采用以下数字? – Daniel
没有。如果你要搜索2,它可能会发现12而不是 – genesis
我的意思是2后用逗号“2”, – Daniel