I want a reg exp for generating SEO-friendly URLs, so things like:
My product name
becomes
My_product_name
This is a long,long,long!!sentence
becomes
This_is_a_long_long_long_sentence
Basically so all non-alphanumeric chars are removed and replaced with underscores.
Any ideas?
preg_replace('/[^a-zA-Z0-9]+/', '_', $sentence)Basically it looks for any sequence of non-alphanumeric characters and replaces it with a single ‘_’. This way, you also avoid having two consecutive _’s in your output.
If it’s for URLs, you probably also want them to be lower-case only:
preg_replace('/[^a-z0-9]+/', '_', strtolower($sentence))