Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jun 2007
    Location
    Canada
    Posts
    49
    Thanks
    1
    Thanked 1 Time in 1 Post

    Regex pattern problem

    I'm trying to write a filter that strips every character not suitable for a filename. So basically A-z 0-9 underscore, dash, period. I understand that period has special meaning but can you not escape it by using a backslash before it?

    PHP Code:
    $string "Testing O'Rielly 0123456789..~!@#$%^&*/\()_-=+";
    $pattern '/[^A-Za-z0-9 _-\.]/';

    echo 
    $string." : ".strlen($string)."<br />";
    $string preg_replace($pattern'',$string);
    echo 
    $string." : ".strlen($string)."<br />"
    This returns a blank string. If I remove the backslash + period I get all the other characters in the pattern.

    What am I missing?

    Thanks

  • #2
    ess
    ess is offline
    Regular Coder
    Join Date
    Oct 2006
    Location
    United Kingdom
    Posts
    866
    Thanks
    7
    Thanked 30 Times in 29 Posts
    Hi Nightchild

    Try the following
    Code:
    // replace everything with '_'
    $string = preg_replace('/[^a-z0-9_\.]/i', '_', $string);
    // if file name ends with '_' remove it from the end of the file
    $string = preg_replace('/_*$/i', '', $string);
    I would use a function so you can reference it more than once, for example
    Code:
    function checkFileName( $string ) {
    // replace everything with '_'
    $string = preg_replace('/[^a-z0-9_\.]/i', '_', $string);
    // if file name ends with '_' remove it from the end of the file
    $string = preg_replace('/_*$/i', '', $string);
    return $string;
    }
    Cheers,
    Ess

  • #3
    New Coder
    Join Date
    Jun 2007
    Location
    Canada
    Posts
    49
    Thanks
    1
    Thanked 1 Time in 1 Post
    Thanks for the assist ESS...

    As it turns out (took a break from this), the minus sign must have special meaning and I missed it in the docs. I escaped the minus sign and everything works fine.

    One note: Using "A-z0-9" only will allow the ^, backslash, and underscore characters to get through unless I use "A-Za-z". I noticed this on the two servers I have access to (Linux SMESRVR and a Windows WAMP).

    PHP Code:
    $string "Testing O'Rielly 0123456789..~!@#$%^&*/\()_-=+";
    $pattern '/[^A-Za-z0-9 _\-\.]/';

    echo 
    $string." : ".strlen($string)."<br />";
    $string preg_replace($pattern'',$string);
    echo 
    $string." : ".strlen($string)."<br />"
    Yeah - my intent from the start was to make this a function in my functions.inc.php file. I just did it this way to try to figure things out.

    Thanks


  •  

    Posting Permissions

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