openid
openid

Reputation: 125

How do I get the number of characters in PHP?

mb_strlen only gives number of bytes, and it is not what I wanted.

It should work with multibyte characters.

Upvotes: 6

Views: 12296

Answers (7)

RandyMorris
RandyMorris

Reputation: 1264

I am not sure about mb_strlen, but I use just plain old strlen myself...

Upvotes: 0

binaryLV
binaryLV

Reputation: 9122

mb_strlen() with mb_internal_encoding('UTF-8').

Upvotes: 6

coding Bott
coding Bott

Reputation: 4357

If you are using UTF-8 encoding, step through all bytes in the string and count the characters which have the eighth bit not set.

This solution does not need the mb extension.

Upvotes: 0

Arkh
Arkh

Reputation: 8459

You may make use of mb_strlen.

Upvotes: 11

alditis
alditis

Reputation: 4817

strlen(): Returns the number of bytes rather than the number of characters in a string.

$name = "Perú"; // With accent mark
echo strlen($name); // Display 5, because "ú" require 2 bytes.

$name = "Peru"; // Without accent mark
echo strlen($name); // Display 4

mb_strlen(): Returns the number of characters in a string having character encoding. A multi-byte character is counted as 1.

$name = "Perú"; // With accent mark
echo mb_strlen($name); // Display 4, because "ú" is counted as 1.

$name = "Peru"; // Without accent mark
echo mb_strlen($name); // Display 4

iconv_strlen(): Returns the character count of a string, as an integer.

$name = "Perú"; // With accent mark
echo iconv_strlen($name); // Display 4.

$name = "Peru"; // Without accent mark
echo iconv_strlen($name); // Display 4

Upvotes: 2

YOU
YOU

Reputation: 123791

mb_strlen($text, "UTF-8");

Upvotes: 14

Russell Dias
Russell Dias

Reputation: 73282

mb_strlen the string being measured for length.

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Directly from the documentation.

Upvotes: 0

Related Questions