Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reg exp wanted for replacing all non-alphanumeric chars with underscores

Tags:

regex

php

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?

like image 528
Ali Avatar asked Nov 12 '09 20:11

Ali


People also ask

How do you replace non-alphanumeric characters?

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!

How do you replace non-alphanumeric characters with an empty string?

The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.

What are non-alphanumeric characters?

Non-alphanumeric characters are characters that are not numbers (0-9) or alphabetic characters.

How do you replace a non-alphanumeric character in Python?

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) .


2 Answers

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))

like image 89
Wim Avatar answered Sep 23 '22 03:09

Wim


 $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, '_');
like image 32
user187291 Avatar answered Sep 22 '22 03:09

user187291