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