Reg exp wanted to replace all non-alphanumeric characters with underscores

I want reg exp to generate 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, all non-alphanumeric characters are deleted and replaced with underscores.

Any ideas?

+3
source share
3 answers

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

+16
source
 $a = preg_replace("/[^A-Za-z0-9]+/", "_", $str);

/\ W +/, ,

, ,

 $a = trim($a, '_');
+4
$str = preg_replace("`[^a-z\d]+`i", "_", $str);
0
source

Source: https://habr.com/ru/post/1722727/


All Articles