Jump to content

How to prevent multiple spaces between words in string for being inserted into database


Recommended Posts

I have registration page where I take school name as one of the fields. Once it is submitted it is checked against existing school names already in table to prevent duplicate registrations. Most schools have more than one word in their name, for example “Sample School.” I had one school that put two spaces between two words and once it was checked against the list it was seen as different name.  How can I make sure that it does not happen again? Is there a simple trick that I do not know, or will I have to do str_replace?

 

Thanks

one method is to strip the extra spaces before they go into the database.

 

Alternatively, at the time of searching, you can split the search word up at the space and join it with a % and do a LIKE query instead of a = query.

 

For example,

 

$search = "Sample School";
$search = preg_replace("~\s+~","%",$search);
$query = "SELECT school FROM tableName WHERE school LIKE '$search'";
This will return the stuff with multiple spaces..but it will return stuff that have anything else inbetween as well, such as "Sample foobar School".

 

If you want to more explicitly only return ones with multiple spaces, you can do a variation of the above, but with a regex approach:

 

$search = "Sample School";
$search = preg_replace("~\s+~",'\s+',$search);
$query = "SELECT school FROM tableName WHERE school REGEXP '$search'";

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can usetrim(), ltrim() orrtrim() to remove it.

  2. `$str = trim(preg_replace('/\s+/',' ', $str);`

     

    This will remove *extra* spaces.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.