SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex to remove non alpha-numeric but leave spaces

    I have this:

    $str = ereg_replace("[^A-Za-z0-9]", "", $str);

    How can I allow spaces to remain in $str?

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    The spaces should remain for that RegEx, can you provide an example where they don't? It will help us see what you're expecting to happen.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually just realised I have another function str_replacing the spaces for dashes and this happens before the function above!

  4. #4
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually I was incorrect. So yes still removing spaces and I'm not sure why. I apply this to the posted field input:

    $formfieldvalue = mysql_real_escape_string(htmlspecialchars(clean($_POST[$formfield])));


    function clean($str){

    $str = ereg_replace("[^A-Za-z0-9]", "", $str);
    return $str;
    }

  5. #5
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Sorry, I was wrong.

    Here you go, note the \s for space and the migration to preg_*

    Code PHP:
    <?php
    function clean($value){
        return preg_replace('~[^0-9a-z\s]~i', '', $value);
    }
     
     
    $string = 'Hello, I\'m Anthony';
     
     
    var_dump(
        clean($string)
    );
     
     
    /*
        string(16) "Hello Im Anthony"
    */

    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  6. #6
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ha! I had just found this same code via Google! Many thanks though


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •