keevitaja Posted October 30, 2009 Share Posted October 30, 2009 i have a directory path /dir/to/somewhere or /dir/to/somewhere/ i need to remove last directory from both examples with one preg_replace so the output would be /dir/to Link to comment https://forums.phpfreaks.com/topic/179685-preg_replace-help-needed/ Share on other sites More sharing options...
cags Posted October 30, 2009 Share Posted October 30, 2009 How about... "~/[\w]+/?$~" Link to comment https://forums.phpfreaks.com/topic/179685-preg_replace-help-needed/#findComment-948072 Share on other sites More sharing options...
keevitaja Posted October 30, 2009 Author Share Posted October 30, 2009 How about... "~/[\w]+/?$~" can you please explain it to me... i'm trying to break for my self this reg exp mystery but with little success! Link to comment https://forums.phpfreaks.com/topic/179685-preg_replace-help-needed/#findComment-948078 Share on other sites More sharing options...
cags Posted October 30, 2009 Share Posted October 30, 2009 ~/[\w]+/?$~ ~ - opening delimiter / - a literal forward slash [\w]+ - 1 or more 'word' characters (letters, digits, and underscores). /? - an optional literal forward slash $ - end of string ~ - closing delimeter It probably makes more sense to the human brain in this case if you read it (and the path) backwards. It will include the trailing slash if there is one, then will work through untill it finds the next(previous) forward slash. These matches characters you would then replace with nothing. $path = preg_replace("~/[\w]+/?$~", "", $path); Link to comment https://forums.phpfreaks.com/topic/179685-preg_replace-help-needed/#findComment-948082 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.