第一個我想替換字符串中的某一位,但不要在PHP改變第一位。查找和替換一個數字,除了在PHP
例如,改變所有4至5:
34 => 35
148 => 158
2449 => 2559
15540 => 15550
43 => 43 (Don't change start 4)
450 => 450 (Don't change start 4)
4540 => 4550 (only change second 4)
第一個我想替換字符串中的某一位,但不要在PHP改變第一位。查找和替換一個數字,除了在PHP
例如,改變所有4至5:
34 => 35
148 => 158
2449 => 2559
15540 => 15550
43 => 43 (Don't change start 4)
450 => 450 (Don't change start 4)
4540 => 4550 (only change second 4)
<?php
$a="4540";//As described in question its an string but it can even be a no auto type conversion will do the rest
$tem=$a[0];
$a=str_ireplace('4', '5', $a);
$a[0]=$tem;
echo $a;//or do what ever you want with $a
效果很好,由於串聯。 – jlee
不客氣。 – 2014-02-16 08:33:05
$ex1 = '34';
$ex2 = '4540';
echo $ex1{0} . str_replace(4, 5, substr($ex1, 1)); // 35
echo $ex2{0} . str_replace(4, 5, substr($ex2, 1)); // 4550
必須爲String - 轉換爲字符串,然後先轉換回,如果你需要爲int。
嘗試這種情況:
<?php
$no="445486";
for($i=1;$i<strlen($no);$i++){
if($no[$i]=="4")
$no[$i]="5";
}
echo $no;
節省第一個字符,在剩餘的部分替換4-> 5,並與保存的第一字符 – Artur