Remove items an array containing only 1 character

Asked

Viewed 135 times

4

I have a 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 array which has only 1 character. For example é, . , O, ,,etc; letter or even some special character such as ,(comma).

How can I remove items from array which contains only 1 character among them letters and special characters?

4 answers

3

You can check the size of the 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 reported as data 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 already helps a little you.

See working here.

2

Good afternoon. Just iterate the array and check each of the values by the strlen function, which returns the size of the string. If it returns 1, you can remove the element and swap it for an empty string, or whatever you prefer. In the code I also used the Trim() function in case you want to remove strings as " is {white space}"

See in the code below:

for ($i = 0; $i < count($arr); $i++) {
if(strlen(trim($arr[$i])) == 1)) {
$arr[$i] = "";

 }
}

I hope it helped =)

  • @Acklay without a problem =)

2

You can use the function array_filter.

Example of use:

$filtrado = array_filter($arr, function($item) {
    if(strlen($item) <= 1) {
        return false;
    }
    return true;
});
  • Why strlen($item) <= 0 ? You can explain it better?

  • It was a typo. It should be <= 1. I edited the answer to agree.

  • I think your approach is good, but you can still optimize.

  • The array_filter function is written in C, only its callback function is php. I can’t see a way to optimize this code anymore.

  • 2

    For example, if this strlen($item) <= 1 is true it already returns true, then why create two returns? You know what I mean?

  • Beware of microtimizations

  • I agree that it can be used too, but I preferred to make the example simpler. Don’t worry that I have no problem with criticism :)

Show 2 more comments

1

If you’re worried about performance ("I’m looking for something also in performance.") should not use the strlen(), use the empty() or isset(), in its place, the difference is minute, but there is.

function remover_palavra_curta(string $string) : bool{
   return isset($string[1]);
}

$arr = array_filter($arr, remover_palavra_curta);

In comparison, I obtained this result, in order of isset, strlen and the mb_strlen.

array(3) {
  [0]=>
  float(0.77282905578613)
  [1]=>
  float(0.81824898719788)
  [2]=>
  float(1.5776748657227)
}

I used this method here for this. The 0 is the isset, the 1 is the strlen and the 2 is the mb_strlen.


The isset and the strlen has a problem with the é for example, since:

$texto = 'é';
var_dump( strlen($texto) === 2 );

Answer, as expected:

bool(true)

This also occurs with the isset(), the $texto[1] also exists. To correct this only using the mb_strlen, or could use the ctype_alpha($texto[1]), but the performance gain would be totally nullified, the faster the use of the mb_strlen.


To get what you want you must give up performance and use the slowest, mb_strlen, he removes all the é as well as the ., as you wish, therefore:

function remover_palavra_curta(string $string) : bool{
   return mb_strlen($string) >= 2;
}
  • mb_strlen($string) > 2 returns values with certain size 2?

  • I wanted to edit that comment of mine, but I exceeded the editing time so I ended up deleting it. But that’s right, in terms of performance.

  • Seria >= actually, but that’s it. To make it true when >= 2 and false when not, thus removing what is less than 2.

Browser other questions tagged

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