Friday, May 21, 2010

How to remove excess whitespaces from a string?



I was looking for a small and quick way to remove excess whitespaces from a string. Sometimes you get SQL statement (or any other string) with whitespaces and need to clean it before your function starts to work with it.

For example:
$sql = "SELECT 
id, field1, field2 ....
FROM table
WHERE status = 1";

And after trying some ways we found, that using preg_replace() function is the best one.

Here the pimpliest way how to do this:
$sql = preg_replace('/\s\s+/', ' ', $sql);


2 comments:

  1. Thats cool. How can I integrate there myphp form?

    ReplyDelete
  2. Anonymous11:29 AM

    $sql = preg_replace('/\s+/', ' ', $sql); do the job. ;-))
    Thanks for the table ... I will test it now.
    What is about the license?

    ReplyDelete