Reputation: 330
I am trying to clean up text that a user could input in a form. I would appreciate any faster methods and extra precautions I could take to make sure that bad code is not injected via this form. ButI am having particular trouble with removing double quotes.
My code is:
str_replace(array('<','>',')','\$','(', '?', '.', ',' ,'!', '-', '+', '/', '\*', '\\', '"'), " ", $text)
But it will not match and remove the slanted quotes, like from MS word, “ to " which is the normal double quotes.
Can you help me with fixing this?
*I am using POST for the form and I am not using the input for anything more than parsing it.
Thanks
This is all that I am trying to do
str_replace(array('"'), " ", $text)
Replace double quotes with a space, but PHP is not recognizing double quotes from a program like Microsoft Word. Thanks
Upvotes: 1
Views: 7610
Reputation: 198219
You could whitelist characters instead of blacklisting some only. Then replace any character that is not whitelisted with the space and afterwards normalize multiple spaces into one space.
$filtered = preg_replace(array('~\W~', '~[ ]{2, }~'), ' ', $text);
Upvotes: 1
Reputation: 1421
The MS smart quotes can be removed with this function.
function convert_smart_quotes($string)
{
$search = array(chr(145),
chr(146),
chr(147),
chr(148),
chr(151));
$replace = array("'",
"'",
'"',
'"',
'-');
return str_replace($search, $replace, $string);
}
Or add them to your code:
str_replace(array('<','>',')','\$','(', '?', '.', ',' ,'!', '-', '+', '/', '\*', '\\', '"', chr(145), chr(146), chr(147), chr(148)), " ", $text)
http://shiflett.org/blog/2005/oct/convert-smart-quotes-with-php
Upvotes: 4
Reputation: 4320
What are you trying to do?
There is htmlspecialchars() function that protects all unknown output from breaking HTML.
Upvotes: 1