Regular Expressions Help

Discussion in 'PHP' started by leony, Jun 5, 2008.

  1. #1
    Hi,

    There are two types of strings:

    1) AAA BBB CCC - DDD &(&) FFF

    2) AAA BBB CCC - DDD

    How can I create a pattern in preg_replace to achieve the following:

    AAA-BBB-CCC-DDD-FFF

    or

    AAA-BBB-CCC-DDD

    I tried the following but not familiar with the syntax:
    
         $patterns[0] = ' '; //white space
         $patterns[1] = ' '.'-'.' ';//white space + '-' + white space
         $patterns[2] = ' '. '&'. ' ';//white space + & + white space
         $replacements[0] = '-';//replace white space with dash
         $replacements[1] = '-';//space - dash - space with dash
         $replacements[2] = '-';//space - & - space with dash
    
    echo preg_replace($patterns, $replacements, $string);
    
    PHP:
    I need a general pattern to get rid of "&" (if there is) and white spaces
    Thanks
     
    leony, Jun 5, 2008 IP
  2. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hmm.. I'm not too good at regexp but maybe this will work:

    preg_replace('/[^a-z0-9]/i','-',$string);
    //it should replace all characters which aren't a-z or 0-9 with "-"

    Let me know if it works :)
    It would need to be changed to get rid of specific things ( & )
    but its a general way to get rid of &+white space
     
    lui2603, Jun 5, 2008 IP
  3. leony

    leony Peon

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi,

    Thanks for the reply, I tried this but it gives:

    AAA-BBB-CCC---DDD-&-FFF

    
    	  $title = preg_replace("/(&| |[\s])*$/i", '', str_replace( ' ', '-', $title ));
    
    PHP:
    The worst case I would not mind & but triple dashes (---) do not seem good.
     
    leony, Jun 5, 2008 IP
  4. aboyd

    aboyd Well-Known Member

    Messages:
    158
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    138
    #4
    $title = preg_replace('/&/', '-', $string);
    $title = preg_replace('/[^a-z0-9]+/i', '-', $title);
    Code (markup):
     
    aboyd, Jun 5, 2008 IP
  5. leony

    leony Peon

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks for the reply Aboyd, it worked!

    So the trick is using [^a-z0-9]+ which replaces triple dashes into one. (+)

    Is that correct?
     
    leony, Jun 5, 2008 IP
  6. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Ah yeh.. My pattern was missing the +

    + matches 1 or more
     
    lui2603, Jun 5, 2008 IP