Question:
I have the following array :
$arr = array('estrela', 'não', 'é', 'up','.','Evitem', 'estrelar',
'abobrinha', 'coisa', 'fugaz', 'de', 'interesse', 'praticamente',
'individual', 'conversa mole','.','Só', 'porque', 'é', 'engraçado',
'não','quer','dizer','que','é','importante','e', 'útil', 'para',
'todos', '.', 'O', 'objetivo', 'do', 'recurso', 'é',
'destacar', 'algo', 'importante','para','as', 'pessoas',
'que', 'não', 'são', 'frequentes', 'no', 'chat', 'abusar',
'dele', 'acaba', 'com', 'sua', 'utilidade', 'Ajam', 'como',
'comunidade', ',', 'pense', 'no', 'que', 'é', 'realmente',
'útil', 'para', 'todos', 'Também', 'não' ,'quer', 'dizer',
'que', 'nada', 'edianamente', 'fútil', 'não', 'pode', 'só', 'sejam',
'mais', 'seletivos', '.');
I would like to remove all items from the array that have only 1 character. For example é
, .
, O
, ,
, etc; being a letter or even some special character like ,
(comma).
How can I remove array items that contain only 1 character among them letters and special characters?
Answer:
You can check the length of characters in a loop, and remove if the value is a character.
Code:
<?php
$arr = ["gato", "g", "stack", "ba", "t", "foo", "à", "é", "bar"];
foreach($arr as $key => $value) {
if (mb_strlen($value) == 1) {
unset($arr[$key]);
}
}
print_r($arr);
Exit:
Array
(
[0] => gato
[2] => stack
[3] => ba
[5] => foo
[8] => bar
)
Output with your array informed as input:
Array
(
[0] => estrela
[1] => não
[3] => up
[5] => Evitem
[6] => estrelar
[7] => abobrinha
[8] => coisa
[9] => fugaz
[10] => de
[11] => interesse
[12] => praticamente
[13] => individual
[14] => conversa mole
[16] => Só
[17] => porque
[19] => engraçado
[20] => não
[21] => quer
[22] => dizer
[23] => que
[25] => importante
[27] => útil
[28] => para
[29] => todos
[32] => objetivo
[33] => do
[34] => recurso
[36] => destacar
[37] => algo
[38] => importante
[39] => para
[40] => as
[41] => pessoas
[42] => que
[43] => não
[44] => são
[45] => frequentes
[46] => no
[47] => chat
[48] => abusar
[49] => dele
[50] => acaba
[51] => com
[52] => sua
[53] => utilidade
[54] => Ajam
[55] => como
[56] => comunidade
[58] => pense
[59] => no
[60] => que
[62] => realmente
[63] => útil
[64] => para
[65] => todos
[66] => Também
[67] => não
[68] => quer
[69] => dizer
[70] => que
[71] => nada
[72] => edianamente
[73] => fútil
[74] => não
[75] => pode
[76] => só
[77] => sejam
[78] => mais
[79] => seletivos
)
You may have to adapt, because it will depend on the coding you are using, and other things can also influence the results, but it helps you a little.
See it working here .