GGGGG
GGGGG

Reputation: 159

Unable to remove white spaces and new lines in a string using php regex

my string is

$str = '             4/151n';

My regex is

preg_match_all('/[^!$|@|!|#|%|\^|&|*|(|)|_|\–|\-|+|=|\\|\/|{|}|\[0-9\]|.|,|\|:|;|"|\'|\s+|→|<|>|\~\[\\r\\n\\t\]~]/', $str, $matches);

My output is

Array
(
    [0] => �
    [1] => n
)

The output I need is

Array
(
    [0] => n
)

Let me explain my requirement clearly. I need to remove all the special characters, numbers, new lines, white spaces from my string. The above regex is working fine for all cases except the above string.

For the above string, I am getting some unknown character in the 0th location. Need to remove that.

Please help me out!

Thanks in advance!

Upvotes: 1

Views: 93

Answers (1)

anubhava
anubhava

Reputation: 784918

I need to remove all the special characters, numbers, new lines, white spaces

You can just use:

$str = preg_replace('/\P{L}+/u', '', $str);
//=> n

Here \P{L}+ matches 1 or more of non-letters with unicode support.

RegEx Demo


Update: Based on this comment from OP:

if I have multiple words in a string, I need to get them in an array

You can use:

if (preg_match_all('/\p{L}+/u', $str, $m))
    print_r($m[0]);

RegEx Demo 2

Upvotes: 3

Related Questions