PHP 5.4.33 Released

strlen

(PHP 4, PHP 5)

strlen文字列の長さを得る

説明

int strlen ( string $string )

与えられた string の長さを返します。

パラメータ

string

長さを調べる文字列。

返り値

成功した場合に string の長さ、 string が空の文字列だった場合に 0 を返します。

変更履歴

バージョン 説明
5.3.0 これより前のバージョンでは、配列を「Array」という文字列とみなして処理していました。 つまり文字列の長さは 5 になります。そして E_NOTICE レベルのエラーが発生します。

例1 strlen() の例

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

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

注意

注意:

strlen() が返すのはバイト数であり、 文字数ではありません。

注意:

配列に対して strlen() を実行すると NULL を返し、 E_WARNING レベルのエラーが発生します。

参考

  • count() - 変数に含まれるすべての要素、 あるいはオブジェクトに含まれる何かの数を数える
  • grapheme_strlen() - 書記素単位で文字列の長さを取得する
  • iconv_strlen() - 文字列の文字数を返す
  • mb_strlen() - 文字列の長さを得る

add a note add a note

User Contributed Notes 11 notes

up
28
chernyshevsky at hotmail dot com
10 years ago
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

<?php
$length
= strlen(utf8_decode($s));
?>

utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.
up
27
tux at tax dot tox
2 years ago
Attention with utf8:
$foo = "bär";
strlen($foo) will return 4 and not 3 as expected..
up
17
vcardillo at gmail dot com
2 years ago
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?

<?php
$foo
= null;
$len = strlen(null);
$bar = '';

echo
"Length: " . strlen($foo) . "<br>";
echo
"Length: $len <br>";
echo
"Length: " . strlen(null) . "<br>";

if (
strlen($foo) === 0) echo 'Null length is Zero <br>';
if (
$len === 0) echo 'Null length is still Zero <br>';

if (
strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (
strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';

if (
strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (
strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';
?>

// Begin Output:
Length: 0
Length: 0
Length: 0

Null length is Zero
Null length is still Zero

!is_null(): $foo is probably null
isset(): $foo is probably null

!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output

So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
up
4
MD ABU SAYEM
5 months ago
Simple code for palindrome
<?PHP
$str
='racecar';
echo
$str.'   ';
$len=strlen($str)-1;
$new='';
for(
$i=$len;$i>=0;$i--){
$new.=$str[$i];
}
echo
$new;
?>
up
8
jasonrohrer at fastmail dot fm
1 year ago
PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0'). 

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

For example, in PHP:

strlen( "te\0st" ) = 5

In C, the same call would return 2.

Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
up
5
basil at gohar dot us
4 years ago
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes
= array('one', 'two', 'three');

if (
strlen($attributes) == 0 && !is_bool($attributes)) {
    echo
"We are in the 'if'\n"//  PHP 5.3
} else {
    echo
"We are in the 'else'\n"//  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.
up
3
bartek at proteus,pl
9 years ago
> Just a precisation, maybe obvious, about the strlen() behaviour:
> with binary strings (i.e. returned by the pack() finction) is made
> a byte count... so strlen returns the number of bytes contained
> in the binary string.

This is not always true. strlen() might be shadowed by mb_strlen().
If that is the case it might treat binary data as unocode string and return wrong value (I just found it out after fighting with egroupware email attachment handling bug).

So, if your data is binary I would suggest using somthing like this (parts of the code from egroupware):

<?php
$has_mbstring
= extension_loaded('mbstring') ||@dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX);
$has_mb_shadow = (int) ini_get('mbstring.func_overload');

if (
$has_mbstring && ($has_mb_shadow & 2) ) {
  
$size = mb_strlen($this->output_data,'latin1');
} else {
  
$size = strlen($this->output_data);
}
?>
--
Bartek
up
1
http://nsk.wikinerds.org
9 years ago
Beware: strlen() counts new line characters at the end of a string, too!

<?php
  $a
= "123\n";
  echo
"<p>".strlen($a)."</p>";
?>

The above code will output 4.
up
-3
Amaroq
5 years ago
When dealing with submitted forms that you've imposed a character limit on, you must remember that functions that count characters consider "\r\n" to be two characters.

<?php
//These will both output 2.
echo strlen("\r\n");
echo
mb_strlen("\r\n");
?>

If I had thought of this starting out, I would have saved myself several hours of trouble trying to get php to cut a message to the same length that my auxiliary javascript validation imposed on it.
up
-1
vaqasuddin
3 months ago
function limit_text( $text, $limit = 100000000000 ) {
        if ( strlen ( $text ) < $limit ) {
            return $text;
        }
        $split_words = explode(' ', $text );
        $out = null;
        foreach ( $split_words as $word ) {
            if ( ( strlen( $word ) > $limit ) && $out == null ) {
                return substr( $word, 0, $limit )."...";
            }
           
            if (( strlen( $out ) + strlen( $word ) ) > $limit) {
                return $out . "...";
            }           
            $out.=" " . $word;
        }
        return $out;
    }

echo limit_text("hello world lorem ipsum",10);
up
-9
packe100 at hotmail dot com
9 years ago
Just a precisation, maybe obvious, about the strlen() behaviour: with binary strings (i.e. returned by the pack() finction) is made a byte count... so strlen returns the number of bytes contained in the binary string.
To Top