How to remove a character that is not a letter in a string?

Asked

Viewed 1,526 times

3

I have a array of strings who returns to me as follows:

Array
(
    [0] => motivação,
    [1] => sentimento33
    [2] => que..
    [3] => 56nos
    [4] => impulsiona\\
    [5] => proporciona
    [6] => investir^^
    [7] => determinado
    [8] => grau?
    [9] => esforço!
)

I want the return to be like this:

Array
(
    [0] => motivação
    [1] => sentimento
    [2] => que
    [3] => nos
    [4] => impulsiona
    [5] => proporciona
    [6] => investir
    [7] => determinado
    [8] => grau
    [9] => esforço
)

Maybe regex would solve this problem, but I haven’t found a solution yet. How can I remove a character that isn’t a letter in a given string?

  • I think it would be enough to use something like [ A-boom].

2 answers

3


You can use preg_replace to remove characters that are not letters from a string. Then you can combine with array_map.

$callback = function ($value) {
    return preg_replace('/\W+/u', '', $value);
};

array_map($callback, $array);

I used the modifier u to recognize accented characters.

The expression \W+ means any character other than words.

  • I didn’t quite understand the /W+, it would not be better just to use the negation "marker" and to disguise what is not a-zA-Z by an empty string?

  • \W+ means any "non-word" Character.See on Documentation.

1

In Unicode, The first accented Latin letter has the code \u00c0 ("À") and the last is \u024F ("y"). You can select all letters using the basic (a-zA-Z) and the range between these two special characters. Thus:

[a-zA-Z\u00C0-\u024F]

And since they’re bracketed, denial is easy:

[^a-zA-Z\u00C0-\u024F]

Now just apply. You can try it on the browser console:

"Açaí, lingüiça, outras comidas acentuadas etc.".replace(/[^a-zA-Z\u00C0-\u024F]/g, "");

Note that you also remove the spaces and punctuation. Add a gap in square brackets if you want to preserve spaces between words, commas and dots if you want to keep score etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.