Search code examples
phpregexpreg-replacefilepathsanitization

Sanitize filepath string and only allow 1 trailing slash at the end


I need to remove non alphanumeric characters except _ (underscore) and - dash and only one / (forward slash) from the end of a string.

$string = 'controller_123/method///';

or

$string = 'controller_123/method/';

Both should return: 'controller_123/method/';

What I have tried up to now:

$string = preg_replace('/[^a-zA-Z0-9_]\/$/', '', $string);

Solution

  • You can use preg_replace with arrays of patterns and replacements; the first to remove non-alphanumeric characters other than _, - and /, and the second to remove all but the last trailing /:

    $string = 'controller_123/method///';
    echo preg_replace(array('#[^\w/-]+#', '#/+$#'), array('', '/'), $string);
    

    Output:

    controller_123/method/
    

    Demo on 3v4l.org

    The regex can be improved by noting that we want to remove all / before the one at the end of the line, and using a positive lookahead to match those. Then all matches can simply be replaced with an empty string:

    $string = 'contr*@&oller_123////method///';
    echo preg_replace('#[^\w/-]+|/(?=/+$)#', '', $string);
    

    Output:

    controller_123////method/
    

    Demo on 3v4l.org