This post provides a function, but it cannot handle non-latin characters.
That's because URLs can't have non-latin/ASCII characters.
Browsers might show non-latin characters to you, but it's just a user interface feature.
For example, if you visit this Wiktionary URL:
https://en.wiktionary.org/wiki/わかもの#Japanese, you browser URL encodes the japanese characters to get the real URL:
https://en.wiktionary.org/wiki/%E3%82%8F%E3%81%8B%E3%82%82%E3%81%AE#Japanese then URL decodes it when displaying the URL. The version with the percentage signs is the real URL.
Likewise with any other non-ASCII character codes, e.g. Arabic. If you create a post with the slug
わかもの then save and check the database, you will not see
わかもの, you will see
%e3%82%8f%e3%81%8b%e3%82%82%e3%81%ae. Likewise the UI will show you the Japanese characters, but if you copy the link, you get the encoded version.
If we then update the database and change the slug of the post to
わかもの, the post now can't be loaded, and we get a 404. That's because the slug is invalid and it's not possible to load a URL that matches that slug.
yes, I need non-latin characters to be encoded as %xx
You need to
echo urlencode( $slug )