Forum Moderators: coopster

Message Too Old, No Replies

extra space between words in variable

how to remove extra space between strings in variable

         

uckc

2:43 am on Oct 13, 2008 (gmt 0)

10+ Year Member



Hi,

Let's say I have a variable named $var and the value assigned to it is "word1 word2 word3"

is there anyway to remove the extra spaces in between the words, and keep only 1 space? I tried trim function, but it seems to only cut off the spaces around the entire string. With str_replace, I can shorten 2 spaces to 1, but it won't work if there's 3+ spaces.

Can anyone help please?

uckc

2:45 am on Oct 13, 2008 (gmt 0)

10+ Year Member



the forum automatically trimmed the extra spaces I put in between word#

The value of $var should be "word1---word2------word3". Read the dashes as whitespaces

uckc

3:42 am on Oct 13, 2008 (gmt 0)

10+ Year Member



To clarify, here's the situation:

I'm using a basic php/mysql search script I found. Basically the script trims the search string, separates the string into independent keywords with explode() for the search and adds <b></b> tags around the keywords found in the MySQL data when it's echo'ed. Now the problem is, if the user enters more than 1 space in between keywords when doing a search, the script will count any additional blank space as a keyword, and it echoes any entries in the database that has a blank space!

I want to strip out extra blank spaces in between words before it uses explode to separate the string into pieces...

[edited by: coopster at 2:25 pm (utc) on Oct. 13, 2008]
[edit reason] removed url [/edit]

cameraman

5:35 am on Oct 13, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about
$var = preg_replace('#\s{2,}#',' ',$var);

uckc

7:12 am on Oct 13, 2008 (gmt 0)

10+ Year Member



Nice, it works! Thank you cameraman!