Hi there,
I need to replace single quote character to two single quotes then I can update the table in SQL server. For example, change the name "O'DONNELL" to "O''DONNELL". I tried to use preg_replace to do it but it seems the ' charater is so special that I cannot do it. Any help is appreciated.
Thanks in advance.
Yolande
how to replace ' character using preg_replace
Moderator: General Moderators
There is no need to replace, if you are escaping correctly 
When you say SQL Server, do you mean MS SQL Server?
Anywho, if you really needed to change all single quotes to doubles:
When you say SQL Server, do you mean MS SQL Server?
Anywho, if you really needed to change all single quotes to doubles:
Code: Select all
$string = str_replace("'", '"', $string);- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland
The SQL language uses quotes (single) to encapsulate string values. So what you need to do is escape the single quote:
O\'DONNELL
This \ tells SQL (except in MSSQL) to ignore the quote following the slash. So this is storable to the database and should produce no errors. Escaping also escapes other special characters - esp. ones that can be used to create an SQL Injection. You should filter all input and escape all output.
MSSQL (back to your question) uses a double quote to escape single quotes.
Your best bet is a REGEX free attempt using:
O\'DONNELL
This \ tells SQL (except in MSSQL) to ignore the quote following the slash. So this is storable to the database and should produce no errors. Escaping also escapes other special characters - esp. ones that can be used to create an SQL Injection. You should filter all input and escape all output.
MSSQL (back to your question) uses a double quote to escape single quotes.
Your best bet is a REGEX free attempt using:
Code: Select all
$data = str_replace("'", "''", $data);