Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

PHP remove non characters from a string

  • 03-11-2007 07:29PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 6,683 ✭✭✭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, Registered Users 2 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