\n (return carriages) in preg_replace

Discussion in 'PHP' started by bannthis, Sep 28, 2007.

  1. #1
    This adds a new line for every whitespace character:

    $after=preg_replace('/\s+/','\n\n',$before);

    I need it to replace any new line that contains extra whitespace characters with just a new line. I THOUGHT it should look something like this:

    $after=preg_replace('/\n/\s+//\n','\n\n',$before);

    But it doesn't work! Any ideas? Thanks!
     
    bannthis, Sep 28, 2007 IP
  2. Collin1000

    Collin1000 Peon

    Messages:
    28
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Here the the correct format for preg_replace

    
    $patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                       '/^\s*{(\w+)}\s*=/');
    $replace = array ('\3/\4/\1\2', '$\1 =');
    echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
    
    Code (markup):
    
    $str = 'foo   o';
    $str = preg_replace('/\s\s+/', ' ', $str);
    
    Code (markup):
    http://us3.php.net/preg_replace
     
    Collin1000, Sep 28, 2007 IP
  3. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #3
    Try this:
    $after = preg_replace('/\A\s+\Z/','',$before);

    Or this:
    $after = preg_replace('/\n\s+\n/',"\n\n",$before);
     
    krt, Sep 28, 2007 IP
  4. msaqibansari

    msaqibansari Peon

    Messages:
    84
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4

    hmm lets try this code.
     
    msaqibansari, Sep 28, 2007 IP
  5. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #5
    Umm... yet another lapse on concentration.

    The first one should be:
    $after = preg_replace('/^\s+$/m', '', $before);
    Code (markup):
    The second one should still be fine if you prefer it.
     
    krt, Sep 28, 2007 IP
  6. bannthis

    bannthis Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Thanks for all your replies!

    $after = preg_replace('/\n\s+\n/',"\n\n",$before);

    Worked perfectly!
     
    bannthis, Oct 1, 2007 IP