469,636 Members | 1,527 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,636 developers. It's quick & easy.

Removing extra spaces between words

code green
1,726 Expert 1GB
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';

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

echo '<br>After';
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
2 9289
5,058 Expert 4TB

You could try regular expressions. Like:
Expand|Select|Wrap|Line Numbers
  1. preg_replace('/ +/', ' ', $str);
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
1,726 Expert 1GB
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.

Similar topics

5 posts views Thread by Marco Gallo | last post: by
11 posts views Thread by gopal srinivasan | last post: by
12 posts views Thread by Magix | last post: by
3 posts views Thread by Ray Stevens | last post: by
4 posts views Thread by dave | last post: by
11 posts views Thread by George Sakkis | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.