1

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!

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

9 Comments

I am getting 0 as my output for this, not getting n
Works for me. What PHP version are you using? Try: $str = preg_replace('/\P{L}+/u', '', $str);
@anubhava Just noticed that +1 :)
@anubhava if I have multiple words in a string, I need to get them in an array. For example, if my string is " 4/151abc!@#n", then my output should be array([0] => abc,[1] => n). For this, I need to use, preg_match_all, How can I write my regex for that. Hope you understand what I am saying!
@anubhava ,The final update is working fine for me, can you explain what is p{L} about this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.