Insert character in a specific position

Asked

Viewed 9,028 times

6

Problem

How to insert a character in a specific position?

Example

In my case in the fourth character

str = 30000000
gostaria que ela ficasse assim: 3000.0000
  • I think the substr will solve your problem then: http://php.net/manual/en/function.substr.php with it you can separate the string and put the "." in the middle

2 answers

25


PHP already has native function for this:

$resultado = substr_replace($original, '.', $posicao, 0);


Parameters:

  • String original

  • Characters to be inserted in position

  • Position (positive from the beginning of the string, negative from the end of the string)

  • Number of characters to remove at that position.


Applying to your case:

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

More details in the manual:

http://php.net/manual/en/function.substr-replace.php

13

Solution

  • I created a function to make it easier to work and so it can be reused elsewhere.

  • I use the function substr to take from option "0" to the position passed as parameter, in the example in question to position "4", returning then "3000".

  • Again using the function substr to catch the end of string, just stating the quantity, in case "4", returning me the last 4 digits of the string "0000".

  • To get a little more dynamic the function, I put a parameter the character that will be inserted in the middle of the string, in the example in question ".".

  • And finally I concateno the whole string forming "3000.0000".

Code

function insertInPosition($str, $pos, $c){
    return substr($str, 0, $pos) . $c . substr($str, $pos);
}

$str = "30000000";
echo insertInPosition($str, 4, '.');

Exit

3000.0000

Execute

Completion

It is an interesting way to solve the problem, however there is already a method of PHP itself that solves this problem, and this answer was given by our friend Bacchus here.

  • perfect guy! thank you so much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.