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

$var=‘1-23456’[/COLOR]

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)

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

Look at the “parameters” section, especially length.

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

INSERT(str,pos,len,newstr)

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_insert

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 abcdexample.com 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?

Thanks

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


SELECT CONCAT(
    SUBSTRING_INDEX('abcdexample.com', SUBSTRING('abcdexample.com', -11), 1),
    '@',
    SUBSTRING('abcdexample.com', -11)
);

Result: abcd@example.com

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.