Search code examples
phppsqltrim

How can I remove white spaces in a psql insert?


I have a text input:

<label for="pt"><b style="color:white"> Company name </b></label>
        <input type="text" name="company" maxlength="100" required>

And I want to insert into a psql database:

$comp= $_POST["company"];
$comptr = trim($comp);

When I have inserted it nothing happened. The data in the table remained the same with multiple whitespaces

here is the insert:

$queryres = "insert into company (v1, v2, ...) VALUES ('$comptr ','$v2', ...)";  
$resultsel = pg_query($con, $queryres);

Example:

I wrote this in the input:

  "     TEST     COMP.  "

in the table stayed this:

"     TEST     COMP.  "

and I want to change to this:

"TEST COMP."
    

Solution

  • You can delete multiple whitespaces within a text not with trim() but quite well with preg_replace(). Make a combination of trim() and preg_replace().

    $comp = $_POST["company"];
    echo trim(preg_replace('/\s+/', ' ', $comp));
    
    // putput: TEST COMP.
    

    preg_replace() https://www.php.net/manual/de/function.preg-replace.php

    trim() https://www.php.net/manual/de/function.trim.php