If encode (ISO-8859-1) is properly configured, the functions strlen()
and strrev()
function as expected, if you are using UTF-8, prefer the approach below.
stlen()
It does not count the number of characters but the byte, a practical example is input ação
returns 6 (bytes) instead of 4 (characters), for characters with multibite find use mb_strlen()
. >
strrev()
suffers from the same problem, it does not handle multibyte characters so it does not make the inversion correctly, in that case use regex to resolve the job.
Example with strlen()
& strrev()
$str = 'AÇÃO';
printf("%s - %s caracteres - invertido: %s", $str, strlen($str), strrev($str));
Saida:
AÇÃO - 6 caracteres - invertido: O�Ç�A
Example with regex & mb_strlen()
function mb_strrev($str){
preg_match_all('/./us', $str, $ar);
return implode('', array_reverse($ar[0]));
}
$str = 'AÇÃO';
printf("%s - %s caracteres - invertido: %s", $str, strlen($str), strrev($str));
Saida:
AÇÃO - 4 caracteres - invertido: OÃÇA