替换字符在字符串中的位置 [英] Replace character's position in a string

查看:156
本文介绍了替换字符在字符串中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如何用X替换字符串的第二个和第三个字符,以使string变为sXXing?

In PHP, how can you replace the second and third character of a string with an X so string would become sXXing?

字符串的长度将固定为六个字符.

The string's length would be fixed at six characters.

谢谢

推荐答案

这取决于您在做什么.

在大多数情况下,您将使用:

In most cases, you will use :

$string = "string";
$string[1] = "X";
$string[2] = "X";

这会将$ string设置为"sXXing",以及

This will sets $string to "sXXing", as well as

 substr_replace('string', 'XX', 1, 2);

但是,如果您希望采用一种完美的方式进行剪切,则应该注意编码.

But if you want a prefect way to do such a cut, you should be aware of encodings.

如果您的$ string是我很喜欢重庆,则输出将是×XX很喜欢",而不是我XX欢重庆".

If your $string is 我很喜欢重庆, your output will be "�XX很喜欢" instead of "我XX欢重庆".

一种避免编码问题的完美"方法是使用 PHP MultiByte字符串扩展.

A "perfect" way to avoid encoding problems is to use the PHP MultiByte String extension.

还有一个自定义的mb_substr_replace,因为尚未实现:

And a custom mb_substr_replace because it has not been already implemented :

function mb_substr_replace($output, $replace, $posOpen, $posClose) {
    return mb_substr($output, 0, $posOpen) . $replace . mb_substr($output, $posClose + 1);
}

然后输入代码:

echo mb_substr_replace('我很喜欢重庆', 'XX', 1, 2);

将向您显示我XX欢重庆.

will show you 我XX欢重庆.

这篇关于替换字符在字符串中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆