PHP 函数替换第 (i) 个位置的字符

问题描述 投票:0回答:6

PHP 中是否有一个函数可以接收一个字符串、一个数字(

i
)和一个字符(
x
),然后将位置(
i
)处的字符替换为(
x
)?

如果没有,有人可以帮我实现吗?

php string replace
6个回答
67
投票
$str    = 'bar';
$str[1] = 'A';
echo $str; // prints bAr

或者你可以使用库函数

substr_replace

$str = substr_replace($str,$char,$pos,1);

14
投票

我很惊讶为什么没有人记得substr_replace()

substr_replace($str, $x, $i, 1);

4
投票

Codaddict是正确的,但是如果你想要一个功能,你可以尝试...

function updateChar($str, $char, $offset) {

   if ( ! isset($str[$offset])) {
       return FALSE;
   }

   $str[$offset] = $char;

   return $str;

}

有效!


1
投票
function replace_char($string, $position, $newchar) {
  if(strlen($string) <= $position) {
    return $string;
  }
  $string[$position] = $newchar;
  return $string;
}

在 PHP 中将字符串视为数组是安全的,只要您不尝试更改字符串末尾后的字符即可。请参阅手册关于琴弦


0
投票
implode(':', str_split('1300', 2));

返回:

13:00

对于某些信用卡号码(例如 Visa)也非常有用:

implode(' ', str_split('4900000000000000', 4));

返回:

4900 0000 0000 0000

str_split — 将字符串转换为数组


0
投票

substr_replace()
能够用另一个字符串替换给定字符串中从 x 偏移量(正或负)开始的 ncharacters 字节数,并且有一个可选参数用于限制消耗的 characters 字节数在注入替换字符串之前。

多字节字符串可以使用,但偏移量和长度参数将计算多字节字符的每个字节。

示例:(演示

echo substr_replace('stack',  'i',    2,  1);  // stick
echo substr_replace('stack',  'u',   -3,  1);  // stuck
echo substr_replace('stack',  'o',    1,  2);  // sock
echo substr_replace('stack',  'ge',  -2,  2);  // stage
echo substr_replace('stack',  'bri',  0,  3);  // brick
echo substr_replace('stack',  'hre',  1, -1);  // shrek
echo substr_replace('stack',  'hre', -4, -1);  // shrek
echo substr_replace('stack',  'y',    3,  0);  // stayck   ...consume no bytes
echo substr_replace('stack',  'y',    3);      // stay     ...consume remaining bytes
echo substr_replace('voilà',  'ci',  -2);      // voilci   ...à has two bytes
echo substr_replace('voilà',  'ci',  -3);      // voici    ...à has two bytes
echo substr_replace('sûreté', '',     4);      // sûr      ...û has two bytes
© www.soinside.com 2019 - 2024. All rights reserved.