(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.
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).
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.
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..
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.
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.
bradmwalker at cableone dot net (2007-07-01 03:48:56)
want a predicate that tests a string for emptiness? use strlen instead of empty(). strlen only returns a false-equivalent value for ''.
example:
<?php
// takes string_array and returns an array without any values w/empty strings
function filter_empties ($string_array) {
// note: the immensely retarded empty() function returns true on string '0'
// use strlen as empty string predicate
return count($string_array) ? array_filter ($string_array, 'strlen') : $string_array;
}
?>
topera at gmail dot com (2007-06-27 08:32:43)
<?php
//------------------------------------------
// This function returns the necessary
// size to show some string in display
// For example:
// $a = strlen_layout("WWW"); // 49
// $a = strlen_layout("..."); // 16
// $a = strlen_layout("Hello World"); // 99
//------------------------------------------
function strlen_pixels($text) {
/*
Pixels utilized by each char (Verdana, 10px, non-bold)
04: j
05: I\il,-./:; <espace>
06: J[]f()
07: t
08: _rz*
09: ?csvxy
10: Saeko0123456789$
11: FKLPTXYZbdghnpqu
12: A?BCERV
13: <=DGHNOQU^+
14: w
15: m
16: @MW
*/
// CREATING ARRAY $ps ('pixel size')
// Note 1: each key of array $ps is the ascii code of the char.
// Note 2: using $ps as GLOBAL can be a good idea, increase speed
// keys: ascii-code
// values: pixel size
// $t: array of arrays, temporary
$t[] = array_combine(array(106), array_fill(0, 1, 4));
$t[] = array_combine(array(73,92,105,108,44), array_fill(0, 5, 5));
$t[] = array_combine(array(45,46,47,58,59,32), array_fill(0, 6, 5));
$t[] = array_combine(array(74,91,93,102,40,41), array_fill(0, 6, 6));
$t[] = array_combine(array(116), array_fill(0, 1, 7));
$t[] = array_combine(array(95,114,122,42), array_fill(0, 4, 8));
$t[] = array_combine(array(63,99,115,118,120,121), array_fill(0, 6, 9));
$t[] = array_combine(array(83,97,101,107), array_fill(0, 4, 10));
$t[] = array_combine(array(111,48,49,50), array_fill(0, 4, 10));
$t[] = array_combine(array(51,52,53,54,55,56,57,36), array_fill(0, 8, 10));
$t[] = array_combine(array(70,75,76,80), array_fill(0, 4, 11));
$t[] = array_combine(array(84,88,89,90,98), array_fill(0, 5, 11));
$t[] = array_combine(array(100,103,104), array_fill(0, 3, 11));
$t[] = array_combine(array(110,112,113,117), array_fill(0, 4, 11));
$t[] = array_combine(array(65,195,135,66), array_fill(0, 4, 12));
$t[] = array_combine(array(67,69,82,86), array_fill(0, 4, 12));
$t[] = array_combine(array(78,79,81,85,94,43), array_fill(0, 6, 13));
$t[] = array_combine(array(60,61,68,71,72), array_fill(0, 5, 13));
$t[] = array_combine(array(119), array_fill(0, 1, 14));
$t[] = array_combine(array(109), array_fill(0, 1, 15));
$t[] = array_combine(array(64,77,87), array_fill(0, 3, 16));
// merge all temp arrays into $ps
$ps = array();
foreach($t as $sub) $ps = $ps + $sub;
// USING ARRAY $ps
$total = 1;
for($i=0; $i<strlen($text); $i++) {
$temp = $ps[ord($text[$i])];
if (!$temp) $temp = 10.5; // default size for 10px
$total += $temp;
}
return $total;
}
?>
Rafael Pereira dos Santos
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
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.
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.
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.