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);
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/
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/