John Magnolia John Magnolia - 4 months ago 14
PHP Question

Convert string to safe name for class

I have a dynamic menu that I need to convert into background images using CSS classes. I would like to convert the label into a safe class name for the css.

An example being:
- Convert string: 'Products & Sunflowers'
- Into a string that contains only a-z and 1-9. The above would be converted into a validate string that can be used as a class name eg: 'products_sunflowers'

tsi tsi
Answer

I use this:

preg_replace('/\W+/','',strtolower(strip_tags($className)));

It will strip all but letters, convert to lower-case and remove all html tags.