How do you strip whitespace from user submitted data that is not an array PHP?
I was wondering how can I strip white space from ele开发者_Python百科ments that are just whitespace and whitespace from all elements from user submitted data using PHP?
lets say if a tag is stripped how can I stop that from entering the database?
$sRaw = $_POST[ 'data' ];
$sTrimmed = trim( $sRaw );
if( $sRaw === $sTrimmed ) {
// DB insert code
} else {
// Message was trimmed, show user an error
}
Very simple.
$string = " Whats up I'm cool?";
$string = trim($string);
$string = str_replace(" ", " ", $string);
$string = str_replace(" ", " ", $string);
echo $string; //output is "Whats up I'm cool?"
The reason is for this is because trim()
removes any whitespace which is deemed useless thus reducing the total size of the string. The only thing is trim()
only removes the whitespace at the beginning and end, so I've added two str_replace()
which have been set to remove unwanted whitespace, and because if there's " " (three spaces) one str_replace()
won't cut it so I've added it twice, and if you want to, you can add a cycle using foreach()
which will trim it until there's no whitespace left but I have wrote it in the basic form as that's what you're asking for.
Depends on the white space... but I believe you are asking about trim() which removes starting and ending whitespace.
echo trim(" v "); //results in "v"
精彩评论