Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Escaping quotes in TEXT

Status
Not open for further replies.

Uzibat

Programmer
Dec 13, 2002
10
GB
I am using Perl to write some simple MySQL queries. My problem is that I am taking in a string that may contain either single quotes or double quotes and I want to store this string in a TEXT field.

It's obvious that I need to escape the single and double quotes within this string but how would I do this as the following substitution regular expression doesn't seem to work (it is only trying to escape double quotes).....

$reviewText =~ s/"/\"/g;

This is my first real Perl program and regular expressions still confuse me so any help would be much appreciated!

 
Code:
$reviewText =~ s/(["'])/\\$1/g;

$reviewText =~ s/
(   start remembering the back reference
[   start character class
"'  enter characters in class
]   end character class
)   end back reference
/   end match, begin substitution
\\  add backslash (must be escaped, hence two of them)
$1  the back reference (what was between the () in the search)
/g; lather rinse repeat

Such would turn
Code:
"as'd'f"
into
Code:
\"as\'d\'f\"
, if that's what you were after. If not, hope it helped. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
See thread219-450610

The correct method for doing what you ask is to use the [tt]quote()[/tt] method of your DBH object.
 
Personally I prefer the regex method to the quote() method, as several DBI installations have returned errors on code using the quote() function, specifically that it is undefined.
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
Thanks for the help. I went back to the code and after a bit of experimenting, found that I hadn't escaped the back slash. Put this in and ended up doing two passes (one for single quotes and one for double) but I will be changing this for the regex posted above - far more efficient!

/g - lather, rinse, repeat Hehe - I like it! That shall be going in as a comment! ;

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top