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

Asked

Viewed 312 times

-1

Well, I need to count the number of characters of a word in PHP, but without using strlen and also any other type of specific function, the point is that I don’t know how to do it. Could someone give me some idea or if you present me an idea, could you explain it to me??

  • And why can’t you use strlen?

  • 2

    This is good, can not use PHP functions but want to use PHP.

  • can use Empty() ?

  • String in which encoding? If it is not ASCII starts to get complicated.

  • A String with any value

  • Explain why you can’t use PHP functions to be clearer.

  • Empty() may use

  • I am learning PHP and my advisor told me to try to do without specific functions, but I was not able to think of anything, but now I’m testing here, I think I should achieve

  • It will depend on the encoding of the tb page.

  • Page encoding is just an input with a button, while in PHP I am extracting the input value and storing it in a variable

  • And then you got?

Show 6 more comments

3 answers

0

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

For every existing position he adds '1' on the counter

<?php
$palavra = "abacaxi"; // 7 letras
$i = 0;
while(!empty($palavra[$i])){
  $i++;
}
echo $i;
?>
  • Thank you for helping me

  • If you put "abácaxi" it will return 8... an accent on "á".

  • /\ I didn’t know. I’ll try to think of something

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.

See this table: https://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dec

This way, the code below makes this kind 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;

Will show: 6

(See the code working on https://ideone.com/Gk8JFS)

  • falls into the same problem that @dvd spoke in my reply

  • @VME, truth, I changed the code.

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

Browser other questions tagged

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