Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP remove non characters from a string

Options
  • 03-11-2007 8:29pm
    #1
    Registered Users Posts: 648 ✭✭✭


    hi

    i need to remove all characters that are not letters or numbers from a string.
    does anyone know how i would do this with regular expressions or other -
    ive made some failed attempts but there must be an easy way !

    thank you


Comments

  • Registered Users Posts: 6,511 ✭✭✭daymobrew


    See preg_replace() and PCRE syntax.
    <?php
    $string = 'This is a 1 12 sentence, with - dash ; semi-colon " + ( ) and other 30 chars.';
    $pattern = '/[^\w\d]/';
    $replacement = '';
    echo preg_replace($pattern, $replacement, $string);
    ?>
    
    Returns:
    Thisisa112sentencewithdashsemicolonandother30chars
    
    It removes spaces too. You could add '\s' to the $pattern line to retain them.


  • Closed Accounts Posts: 1,200 ✭✭✭louie


    There is a function that I put togheter and will do just that for you:

    http://www.eire-webdesign.ie/blog/2007/11/01/sanitize-input-from-forms-or-database/


  • Registered Users Posts: 648 ✭✭✭ChicoMendez


    thanks lads - they are great


    one question : for your example daymobrew what do i change the pattern to if i want to allow dots '.' ?


    tnx


  • Closed Accounts Posts: 1,200 ✭✭✭louie


    [php]$pattern = '/[^\w\d\.]/';
    // ad a back-slashed \. like above
    //same goes for few other char. like \- \_ \( \)...
    [/php]


Advertisement