preg_replace('/[^a-zA-Z0-9]+/', '_', $sentence)
Basically, he searches for any sequence of characters other than alphanumeric characters, and replaces it with one "_". This way you also avoid having two consecutive _s in your output.
If this is for URLs, you probably also want them to be lowercase only:
preg_replace('/[^a-z0-9]+/', '_', strtolower($sentence))
source
share