How to invert words and count the total characters

3

As I do via php / html, for example, I have a input user to type anything, and the time that he clicks the "OK" button, I return the word he typed in reverse , and the amount of characters of the word that was typed by it?

I know I'm going to have to use the strlen() and strrev() methods, but I do not know how to do it. can anybody help me? Thankful

    
asked by anonymous 25.02.2016 / 19:31

4 answers

7

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
    
25.02.2016 / 19:44
6

I suggest something like this:

 $input = $_GET['nome_do_campo'];
 $invertido = strrev($input);
 $tamanho = strlen($input);

echo "String invertida: <em>{$invertido}</em>. O tamanho é de <strong>{$tamanho}</strong> caracteres";
    
25.02.2016 / 19:44
5

Simple

<?php

    $string = (isset($_POST['input1'])) ? trim($_POST['input1']) : null;

    $stringInvertida = strrev($string);
    $qntCaracteres = strlen($string);

    echo "Seu texto invertido é: {$stringInvertida} e contem {$qntCaracteres} caractere(s).";

In your HTML form, set the name do input that will receive the string as input1

    
25.02.2016 / 19:42
1

A version with multibyte character support:

$str = '日本語'; // teste essa palavra alienígena
$str = 'Ação'; // ou será que essa palavra é alienígena?

echo 'quantidade de letras: '.mb_strlen($str);
echo PHP_EOL.'<br />inverso: '.join('', array_reverse(preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY)));

The native function strrev() is not multibyte safe, so the implementation using join() , array_reverse() and preg_split() .

The mb_strlen() function is specific to multibyte characters and returns the number of characters. Do not confuse with amount of bytes.

If you want to know the number of bytes, use strlen() .

See the difference

$str = 'Ação';
echo strlen($str).PHP_EOL.'<br />';
echo mb_strlen($str).PHP_EOL;
    
26.02.2016 / 14:38