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?
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced. Copied!
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
Non-alphanumeric characters are characters that are not numbers (0-9) or alphabetic characters.
Use the re. sub() method to replace all non-alphanumeric characters in a string, e.g. new_str = re. sub(r'[^a-zA-Z0-9]', '|', my_str) .
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))
$a = preg_replace("/[^A-Za-z0-9]+/", "_", $str);
or /\W+/ if you want to keep everything that is considered a "letter" in the current locale
after replacement it may be also neccessary to stip leading and trailing underscores
$a = trim($a, '_');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With