By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,310 Members | 1,430 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,310 IT Pros & Developers. It's quick & easy.

Removing extra spaces between words

code green
Expert 100+
P: 1,726
I am trying to write a simple function that will take a string containing an
address line or business name and return it nicely formatted.
By this I mean extra spaces removed and words capitalised.
I also wish it to be legal XML..
The result string is further sent to another function to check
the names and addresses don't appear on a blacklist
which is why the extra spaces need removing.
This is my test function so far
[PHP]function cleanProperNouns($name)
{
$words = explode(' ',strtolower($name));
echo '<br>Before';
print_r($words);

foreach($words as &$w)
$w = trim($w);

echo '<br>After';
print_r($words);
return htmlspecialchars(ucwords(implode(' ',$words)));
}

echo cleanProperNouns('this & is a test name '); [/PHP] It does not remove all the extra spaces in the string.
It looks fine in a browser but source is not.
Has anybody written a function that does something similar or got any better ideas?
Jul 22 '08 #1
Share this Question
Share on Google+
2 Replies


Atli
Expert 5K+
P: 5,058
Hi.

You could try regular expressions. Like:
Expand|Select|Wrap|Line Numbers
  1. preg_replace('/ +/', ' ', $str);
  2.  
This simply looks for a one or more spaces and replaces them all with a single space.

You could of course write a old fashion function that does the exact thing.
It would basically just have to look for a the first occurrence of a white-space, count the number of white-spaces that follow the first one, and replace the lot with a single space.
Jul 22 '08 #2

code green
Expert 100+
P: 1,726
Well done Atli for shocking my brain back into life.
I'm struggling with trim instead of str_replace, preg_replace.
What I was concentrating on was replacing the little loop with an array function / string function combination to clean the data.
I am not 100% sure what all those array functions do and thought maybe somebody has a clever alternative to looping through the array
Jul 23 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.