Updated PHP Windows builds for Brotli security fix

grapheme_strlen

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strlen — Lit la taille d'une chaîne en nombre de graphème

Description

Style procédural

function grapheme_strlen(string $string): int|false|null

Lit la taille d'une chaîne en nombre de graphèmes (et non pas en octets ou caractères).

Liste de paramètres

string

La chaîne à mesurer. Elle doit être une chaîne UTF-8 valide.

Valeurs de retour

La taille de la chaîne en cas de succès, null ou false en cas d'échec.

Exemples

Exemple #1 Exemple avec grapheme_strlen()

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) forme normalisée "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) forme normalisée "D"

print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);

?>

L'exemple ci-dessus va afficher :

6

Exemple #2 Gestion d'une entrée UTF-8 invalide

grapheme_strlen() retourne null ou false en cas d'échec, y compris lorsque l'entrée n'est pas de l'UTF-8 valide. Utiliser intl_get_error_code() et intl_error_name() pour récupérer les détails de l'erreur ICU.

<?php

$string = "\xFF"; // séquence d'octets UTF-8 invalide
$length = grapheme_strlen($string);

if (!is_int($length)) {
    $code = intl_get_error_code();
    printf("grapheme_strlen() a échoué : %s (%d)\n", intl_error_name($code), $code);
} else {
    echo $length, PHP_EOL;
}

?>

L'exemple ci-dessus va afficher :

grapheme_strlen() a échoué : U_INVALID_CHAR_FOUND (10)

Voir aussi

+add a note

User Contributed Notes 1 note

up
10
jonhoggg at gmail dot com
4 years ago
You can use grapheme_strlen() to count emojis as a single character:

<?php
    echo strlen('🏴󠁧󠁢󠁥󠁮󠁧󠁿'); //28 - oh no
    echo mb_strlen('🏴󠁧󠁢󠁥󠁮󠁧󠁿'); // - closer, but no
    echo grapheme_strlen('🏴󠁧󠁢󠁥󠁮󠁧󠁿'); //1 - Bingo
?>
To Top