Tuesday, August 6, 2013

[PHP][Sharing] Trim all $_POST value in PHP

Today found some clean code from stackoverflow to remove space at begining and the end of value. And I think I would be nice for sharing. If there are these 3 php POST value from a HTML form, and some value including space at the begining or at the end:

$_POST["name"] = "Sam Yi ";
$_POST["title"] = " This title is strange";
$_POST["interest"] = "I have no interest";

If you echo the $_POST value,
<?php
echo $_POST["name"].",";
echo $_POST["title"].",";
echo $_POST["interest"].".";
?>

you will got this result :(useless space are highlighted in yellow)
Sam Yi , This title is strange,I have no interest.

To remove the useless space at begining or the end of the value, you can use a foreach to load all $_POST value to trim.
<?php
        foreach ($_POST as $key => $val){
            $_POST[$key] = trim($val);
        }

        echo $_POST["name"].",";
        echo $_POST["title"].",";
        echo $_POST["interest"].".";
?>
       
You will get this result:
Sam Yi,This title is strange,I have no interest.       

Reference:       
http://stackoverflow.com/questions/4710440/php-need-to-trim-all-the-post-variables       

No comments :

Post a Comment