PHP将值1添加到字符串中的位置并替换

时间:2014-03-18 07:24:44

标签: php function

我想用另一个字符替换一个字母,并且还要添加1个值。 我的意思是价值观是动态的

例如我有H9,我想替换为G10

...类似地

  • H2G3
  • H6G7

是否可以使用str_replace()

4 个答案:

答案 0 :(得分:1)

我得到了一个适合我的那个:

$old_string = "H2";
$new_string = "G" . (substr($old_string, 1) + 1);
echo $new_string;

对我来说很好。这只是一个值,但我想你也可以遍历一个数组,只需修改这样的值

foreach($old_values as $v) {
    $new_values[] = "G" . (substr($v, 1) + 1);
}

因此您可以将所有值保存到$ new_string数组

答案 1 :(得分:0)

当然,您可以使用str_replace()

使用

$new = array("G10", "G3", "G7");
$old   = array("H9", "H2", "H6");
$string = str_replace($old, $new, $string);

其中$string是您的原始字符串。

答案 2 :(得分:0)

试试这个

<?php 
$str = "H25";
preg_match_all('!\d+!', $str, $matches);
$str = str_replace($matches['0']['0'], $matches['0']['0']+1, $str, $count);
echo $str;
?>

答案 3 :(得分:0)

更简单的方式......(广义解决方案)

<?php
$str='G10';
preg_match('!\d+!', $str, $digit); //<---- Match the number
$str = substr($str,0,1); //<--- Grab the first char & increment it in the second line
echo ++$str.($digit[0]+1); //"prints" H11

Demo