Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace character's position in a string

Tags:

php

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

like image 832
waraker Avatar asked Oct 16 '25 00:10

waraker


2 Answers

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欢重庆.

like image 173
Alain Tiemblo Avatar answered Oct 17 '25 14:10

Alain Tiemblo


Simple:

<?php
$str = "string";
$str[1] = $str[2] = "X";
echo $str;
?>
like image 36
HamZa Avatar answered Oct 17 '25 13:10

HamZa