©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5)
strlen — 获取字符串长度
$string
)
返回给定的字符串 string
的长度。
string
需要计算长度的 字符串 。
成功则返回字符串 string
的长度;如果 string
为空,则返回 0。
版本 | 说明 |
---|---|
5.3.0 |
Prior versions treated arrays as the string Array, thus returning
a string length of 5 and emitting an E_NOTICE level error.
|
Example #1 strlen() 范例
<?php
$str = 'abcdef' ;
echo strlen ( $str ); // 6
$str = ' ab cd ' ;
echo strlen ( $str ); // 7
?>
Note:
strlen() returns the number of bytes rather than the number of characters in a string.
Note:
strlen() returns
NULL
when executed on arrays, and anE_WARNING
level error is emitted.
[#1] vaqasuddin [2014-06-10 11:04:09]
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);
[#2] MD ABU SAYEM [2014-04-17 05:09:28]
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;
?>
[#3] jasonrohrer at fastmail dot fm [2013-06-13 22:48:24]
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).
[#4] vcardillo at gmail dot com [2012-08-14 03:59:37]
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.
[#5] tux at tax dot tox [2012-08-05 18:54:23]
Attention with utf8:
$foo = "b?r";
strlen($foo) will return 4 and not 3 as expected..
[#6] basil at gohar dot us [2010-06-08 14:03:09]
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.
[#7] Amaroq [2009-03-19 23:51:37]
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.
[#8] bartek at proteus,pl [2005-07-19 05:08:45]
> 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
[#9] http://nsk.wikinerds.org [2005-04-22 09:02:17]
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.
[#10] packe100 at hotmail dot com [2005-03-14 07:07:41]
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.
[#11] chernyshevsky at hotmail dot com [2004-09-05 15:36:44]
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.