Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use preg_split for all special characters

Tags:

regex

php

I want to split a String everytime a special character is found.

I did this :

preg_split("[\\W]", $str);

But this will still allow underscore (and maybe more?)

Is it possible to just say allow a-z A-Z and digits and split on anything that is not one of these?

like image 429
Bart Avatar asked Dec 01 '25 04:12

Bart


1 Answers

You have just answered your question:

preg_split('~[^a-z0-9]~i', $str);

See this regex demo

The [^a-z0-9] negated character class matches any character other than a-z (and A-Z due to the i modifier) and other than a digit (defined with 0-9).

Another way is with using POSIX [:alnum:] character class inside a negated character class:

'~[^[:alnum:]]~'

See regex demo

Note that it is easier to use single char regex delimiters rather than paired ones, my favorite being ~. It is rarely used in regex patterns, and thus I do not have to escape too much in my patterns.

like image 151
Wiktor Stribiżew Avatar answered Dec 02 '25 19:12

Wiktor Stribiżew