SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Cleaning up spaces and punctuations

  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2004
    Location
    London
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cleaning up spaces and punctuations

    The users of my web site don't know where to put spaces around punctuation symbols. For example, after a period, comma or a semicolon there should be a whitespace but not after decimals or thousands-separators in numbers.

    Does anyone have handy a regular expression that cleans up the text in this way?

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,109
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quick-n-dirty.
    PHP Code:
    <?php
    function punctuate($string$chars ',.;'){
      return 
    preg_replace(
        
    sprintf(
          
    '~([%s])(?![0-9\s])~',
          
    preg_quote($chars)
        ),
        
    '$1 ',
        
    $string
      
    );
    }

    echo 
    punctuate('12.00sdg,df.g,sd.g,d3,5664.00.Year 1900.');
    #12.00sdg, df. g, sd. g, d3,5664.00. Year 1900.
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Enthusiast
    Join Date
    Dec 2004
    Location
    London
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks.

    Could you please modify it so that it deletes any whitespaces before the punctuation mark if they exist? I have to admit I'm lost when it comes to regular expressions and your function looks even stranger, with no forward slashes for delimiting patterns and sprintf() which I've never used. :-| I promise I'll get a good regex book.


    Edit: uhhh never mind, I got it. Thanks.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •