Inserting a character into a string

Hi all,

I am trying to find a way to insert a character into a variable after the first character of the variable, and then use this in an SQL query.

[COLOR=“SeaGreen”] i.e. $var=‘123456’

and i want to change this to


This will then be used in an SQL query to select results from the database.

Can I do this in PHP, i’m thinking it wouldn’t be as efficient in SQL.

Thanks in advance

$var = substr_replace($var, '-', 1, 0)

Look at the “parameters” section, especially length.

In MySQL you could also use the INSERT() string function.


mysql> SELECT INSERT('Quadratic',2,0,'-');
| INSERT('Quadratic',2,0,'-') |
| Q-uadratic                  |
1 row in set (0.00 sec)

Just replace str with your data. Hope that helps.

Here is another spin on this question. How do you tell the insert function to start counting from the back of the string?

For example I have a batch of e-mail addresses like how do I tell it to count off 11 places from the back and insert @ character in that spot? Or could I somehow reverse the string and use regular INSERT function?


This may not be the “best” solution, but it works.

    SUBSTRING_INDEX('', SUBSTRING('', -11), 1),
    SUBSTRING('', -11)


Thanks man, I will make sure and try this. I did, however, ended up reversing the strings and inserting the character and then reversing it back again with REVERSE(); INSERT() and REVERSE() again. I know, it’s not as elegant, but it worked.

Another way would be to subtract 10 from the length of the string, and use the result as the start position for insert()

Yeah, but how do you tell it to start subtracting from the back and not from the front?

He means to count the number of characters in the string and subtract 10 from that number. That is where you tell the INSERT function to start inserting from.