How do I insert a character in a specific position? (In my case in the 4th character insert ".").
Example:
str = 30000000
gostaria que ela ficasse assim: 3000.0000
How do I insert a character in a specific position? (In my case in the 4th character insert ".").
Example:
str = 30000000
gostaria que ela ficasse assim: 3000.0000
You can do it this way:
function replaceByPos($str, $pos, $c){
return substr($str, 0, $pos) . $c . substr($str, $pos);
}
$str = "30000000";
echo replaceByPos($str, 4, '.');
I created a function to make it easier to work, at first use of the function substr
it takes the beginning of the string and the second substr
takes the end of the string and concatenates with the desired character or string. >
PHP already has a function for this:
$resultado = substr_replace($original, '.', $posicao, 0);
If you want to count 4 from the left:
$resultado = substr_replace($original, '.', 4, 0);
If you want to count 4 from the right:
$resultado = substr_replace($original, '.', -4, 0);
See both cases working at IDEONE .
More details in the manual: