PHP preg_replace question

Discussion in 'Coding Help' started by ziycon, Jan 5, 2011.

Tags:
  1. ziycon

    ziycon New Member

    The below line will remove all alphanumeric characters, what I'm trying to do is remove all alphanumeric characters but replace all spaces with '-'. Will I just need to have two preg_replace statements or can it be done in the one line?
    Code:
    [COLOR=#0000bb]preg_replace[/COLOR][COLOR=#007700]([/COLOR][COLOR=#dd0000]“/[^a-zA-Z0-9\s]/”[/COLOR][COLOR=#007700], [/COLOR][COLOR=#dd0000]“”[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000bb]$string[/COLOR][COLOR=#007700])[/COLOR]
    So this line:
    would become:

     
  2. php.allstar

    php.allstar New Member

    Hi, try this:

    PHP:
    <?php

         $string 
    'Test data\'s - "testing" ';
         
         
    $patterns = array();
         
    $patterns[0] = '/[^a-zA-Z0-9\s]/';
         
    $patterns[1] = '/\s+/';

         
    $replacements = array();
         
    $replacements[0] = '';
         
    $replacements[1] = '-';
         
         echo 
    preg_replace($patterns$replacementstrim($string));

    ?>
    there's probably a more eloquent way to get rid of the trailing whitespace with a modifier as opposed to using trim() but I can't think of it at this moment!

    Patterns and replacements can be sent as indexed arrays instead of strings as I've demonstrated here.
     
  3. php.allstar

    php.allstar New Member

    ah yes, that trailing whitespace issue was annoying me so I had to find the solution! Try this instead:

    PHP:
    <?php

         $string 
    'Test data\'s - "testing" ';
         
         
    $patterns = array();
         
    $patterns[0] = '/[^a-zA-Z0-9\s]|\s$/';
         
    $patterns[1] = '/\s+/';

         
    $replacements = array();
         
    $replacements[0] = '';
         
    $replacements[1] = '-';
         
         echo 
    preg_replace($patterns$replacements$string);

    ?> 
    Added |\s$ to the first pattern to match the trailing whitespace as well as non alphanumeric characters
     
  4. ziycon

    ziycon New Member

    Nice one, your a star, been bugging me for ages. Thanks again.
     
  5. php.allstar

    php.allstar New Member

    Glad to have helped! Please click the "Thanks" link under my post as seeing it makes me feel all warm and fuzzy!
     

Share This Page