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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3994300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:40:29  来源:igfitidea点击:

PHP function to replace a (i)th-position character

phpstringreplace

提问by vikmalhotra

Is there a function in PHP that takes in a string, a number (i), and a character (x), then replaces the character at position (i) with (x)?

PHP 中是否有一个函数接受一个字符串、一个数字 ( i) 和一个字符 ( x),然后将位置 ( i)处的字符替换为( x)?

If not, can somebody help me in implementing it?

如果没有,有人可以帮助我实施它吗?

回答by codaddict

$str    = 'bar';
$str[1] = 'A';
echo $str; // prints bAr

or you could use the library function substr_replaceas:

或者您可以将库函数substr_replace用作:

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

回答by zerkms

I amazed why no one remember about substr_replace()

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

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

回答by alex

Codaddict is correct, but if you wanted a function, you could try...

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

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

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

   $str[$offset] = $char;

   return $str;

}

It works!

有用!

回答by Emil Vikstr?m

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

It's safe to treat strings as arrays in PHP, as long as you don't try to change chars after the end of the string. See the manual on strings:

在 PHP 中将字符串视为数组是安全的,只要您不尝试在字符串结束后更改字符。请参阅有关字符串的手册:

回答by Amorim

implode(':', str_split('1300', 2));

returns:

返回:

13:00

13:00

Also very nice for some credit card numbers like Visa:

对于像 Visa 这样的一些信用卡号码也非常好:

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

returns:

返回:

4900 0000 0000 0000

4900 0000 0000 0000

str_split — Convert a string to an array

str_split — 将字符串转换为数组