Insert character in specific position

3

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
    
asked by anonymous 07.05.2018 / 18:59

3 answers

5

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. >     

07.05.2018 / 19:08
10

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:

  

link

    
07.05.2018 / 19:13
3

Using the number_format() function:

$str=number_format($str,4,'.','');

Manual:

  

link

    
07.05.2018 / 19:09