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

3

I have a array of strings that returns 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 have not yet found a solution. How can I remove character that is not a letter in a given string ?

    
asked by anonymous 15.04.2017 / 15:32

2 answers

3

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

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

array_map($callback, $array);

I used the u f modifier to recognize accented characters.

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

    
15.04.2017 / 15:55
1

In Unicode, the first accented Latin letter has the code \u00c0 ( "À" / a>) and the last one is \u024F ( " and "). You can select all letters using the basics ( a-zA-Z ) and the range between those two special characters. So:

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

And because brackets are 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 this also removes spaces and punctuation. Add a space in the brackets if you want to preserve spaces between words, commas and periods if you want to keep score etc.

    
15.04.2017 / 15:47