View Full Version : Resolved several regex from post
ggalan
12-21-2011, 07:42 PM
i have an ajax form posting into a sql db and would like to backslash single, double quotes and the backslash itself, this doesnt seem to work from a <input /> field
$old = $_POST['title'];
$newTitle = trim( preg_replace('/\\\\/','\\\\\\\\',$old) ); // backslash a backslash \\
$newTitle = trim( preg_replace( '/[\"]/', '\"', $old ) ); // backslash the double quotes \"
$newTitle = trim( preg_replace( '/[\']/', '\"', $old ) ); // backslash the single quotes \'
mysql_query("UPDATE `mytable` SET title ='$newTitle' WHERE id='$id'");
would i have to turn all those regex into 1 concise statement?
jscheuer1
12-21-2011, 08:28 PM
No. Perhaps you could, perhaps not, or there might be a PHP function or functions that do all those things even more concisely. If you don't though, you would have to chain them. Here's one way:
$old = $_POST['title'];
$newTitle = trim( preg_replace('/\\\\/','\\\\\\\\',$old) ); // backslash a backslash \\
$newTitle = trim( preg_replace( '/[\"]/', '\"', $newTitle ) ); // backslash the double quotes \"
$newTitle = trim( preg_replace( '/[\']/', '\"', $newTitle ) ); // backslash the single quotes \'
mysql_query("UPDATE `mytable` SET title ='$newTitle' WHERE id='$id'");
But I think addslashes():
http://www.php.net/manual/en/function.addslashes.php
will do it all for you in one pass.
ggalan
12-21-2011, 08:58 PM
when i create a file to output the result it almost works, but the single quote is coming out as a double
this was my input
/ \ ' "
$File = "test.txt";
$Handle = fopen($File, 'w');
$Data = "$newTitle";
fwrite($Handle, $Data);
fclose($Handle);
output from text file:
/ \\ \" \"
but in mysql i dont get the backslashes and the single quote comes out as double
/ \ " "
jscheuer1
12-21-2011, 10:00 PM
That's probably something in your regular expression(s). Have you tried addslashes? It's designed for entering data into a database, specifically to escape the \, ' , and " characters. Assuming the rest of your code is right, I think it would go like:
$old = $_POST['title'];
$newTitle = trim( addslashes($old) ); // add slashes
mysql_query("UPDATE `mytable` SET title ='$newTitle' WHERE id='$id'");
ggalan
12-21-2011, 11:53 PM
thank you, that did it. my problem was in the html output. is there a php function that can turn these slashes into a format that is displayable?
<input class='textfield' type='text' title='title' value='a \' \" / \\ v' />
i tried htmlspecialchars() but it doesnt take care of the single quote
re: this did it in the html output
$newTitle = htmlspecialchars($title, ENT_QUOTES);
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.