将URL转换为正确的文件名(Linux / Windows)

I have a script that works with different sites. As a result this script returns 1 csv file for 1 site with a unique filename, based on site URL. Site URL may be different, like

http://test1.com
http://test2.com/testurl
http://test3.com/test/path/

I want to convert URLs to filenames - to remove all characters that can cause conflict in Linux/Windows, to replace them with '_', for example

http://test1.com will be test1com.csv
http://test2.com/testurl will be test2comtesturl.csv
http://test3.com/test/path/ will be test3comtestpath.csv

I can try to use parse_url and concat host and path with replacing '/' and '.' to '_', but I'm not sure that this is the best solution, because URLs can be different and with different characters that can not be used as filename.

You can make a list of URL-safe characters and convert any character that's not in the list into _.

Just be careful of duplicates (site.com/test/x and site.com/text.x, for example), if any. Find a way to handle them.