matthewtbaker Posted October 22, 2012 Share Posted October 22, 2012 Good day! I've tried a few routes but haven't managed a simple approach. Ideally I'd like to use one of PHPs built in functions to make the code cleaner and easier to follow. Basically I need to remove anything after a defined number of occurrences of a character from the example string below; $iLevels = 2; $sUrl = http://www.example.com/products/entertainment/films/dvd/page.html So in this case I need to remove anything after the second to last forward slash, deleting dvd/page.html. The number of forward slashes to remove is variable therefore a flexible solution is needed. Thanks for your help/advice in advance! Matt Link to comment https://forums.phpfreaks.com/topic/269770-remove-characters-after-nth-occurence-of-symbol/ Share on other sites More sharing options...
silkfire Posted October 22, 2012 Share Posted October 22, 2012 Try this: $url = 'http://www.example.com/products/entertainment/films/dvd/page.html'; echo implode('/', array_slice(explode('/', $url), 0, -2)) . '/'; Link to comment https://forums.phpfreaks.com/topic/269770-remove-characters-after-nth-occurence-of-symbol/#findComment-1386941 Share on other sites More sharing options...
salathe Posted October 22, 2012 Share Posted October 22, 2012 Aside: array_slice(explode('/', $url), 0, -2) could be replaced with explode('/', $url, -2). Link to comment https://forums.phpfreaks.com/topic/269770-remove-characters-after-nth-occurence-of-symbol/#findComment-1386965 Share on other sites More sharing options...
matthewtbaker Posted October 26, 2012 Author Share Posted October 26, 2012 Thanks Silkfire worked like a charm. I will try your shorter approach salathe, thank you. Link to comment https://forums.phpfreaks.com/topic/269770-remove-characters-after-nth-occurence-of-symbol/#findComment-1387864 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.