Could you help me count the number of characters of a word in PHP

-1

Well, I need to count the number of characters of a word in PHP, but without using strlen and also any other kind of function specifies, the question is that I do not know how I can do it. Could someone give me some idea or if you give me an idea, could you explain it to me ??

    
asked by anonymous 27.06.2018 / 01:26

3 answers

0

As you yourself said, you could use empty ():

For each existing position it adds '1' to the counter

<?php
$palavra = "abacaxi"; // 7 letras
$i = 0;
while(!empty($palavra[$i])){
  $i++;
}
echo $i;
?>
    
27.06.2018 / 02:31
0

You can access characters from a string as if it were an array.

Note: As warned in the comments, accented characters (UTF-8) occupy two spaces instead of one, so to detect this type of character, we see if its code (ord) has value> = 127.

p>

See this table: link

In this way, the code below does this type of conference, without using PHP functions as you requested.

<?php
$str = "àbcÂef"; // visualmente são 6 caracteres, mas internamente são 8 (2 UTF)
$i = 0; // pointer para a string
$c = 0; // contador de caracteres
while ($str[$i]<>"") {
    if (ord($str[$i]) >= 127) // se for utf, despreza o caractere seguinte
        $i++;
    $c++;
    $i++;
}
echo $c;

Show: 6

(See working code at link )

    
27.06.2018 / 02:37
0

14 letters - 7 letters

$palavra = "àñáçâçí"; // 14 letras 

function tirarAcentos($string){
    return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(ç)/","/(Ç)/"),explode(" ","a A e E i I o O u U n N c C"),$string);
}

$sem = tirarAcentos($palavra);

$i = 0;
while(!empty($sem[$i])){
  $i++;
}
echo $i;  // 7 letras
    
27.06.2018 / 03:37