Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

php - Replace character's position in a string

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends on what you are doing.

In most cases, you will use :

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

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.

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

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

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);
}

Then, code :

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

will show you 我XX欢重庆.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...