Removing extra spaces between words

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    Removing extra spaces between words

    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 cleanProperNoun s($name)
    {
    $words = explode(' ',strtolower($n ame));
    echo '<br>Before';
    print_r($words) ;

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

    echo '<br>After';
    print_r($words) ;
    return htmlspecialchar s(ucwords(implo de(' ',$words)));
    }

    echo cleanProperNoun s('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?
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    You could try regular expressions. Like:
    [code=php]
    preg_replace('/ +/', ' ', $str);
    [/code]
    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.

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      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

      Comment

      Working...