欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

strlen

shiping1 的头像

strlen

(PHP 4, PHP 5)

strlen — 获取字符串长度

说明

int strlen ( string $string )

返回给定的字符串 string 的长度。

参数

 

string

需要计算长度的字符串

 

返回值

成功则返回字符串 string 的长度;如果 string 为空,则返回 0。

更新日志

版本说明
5.3.0Prior 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 NULL when executed on arrays, and an E_WARNING level error is emitted.

 

参见

 

  • count() - 计算数组中的单元数目或对象中的属性个数
  • mb_strlen() - Get string length

 


用户评论:

darren[AT]zoid[DOT]me (14-Mar-2012 07:04)

 

PhoneixS 13-May-2011 05:09 - Update : integers and floats are converted for the purpose of measuring the string length. But the original variables are left unaltered.

$howdy = 101;
$new = strlen($howdy);

var_dump($howdy); // int(101) - notice, its still an integer
var_dump($new); // int(3)

 

PhoneixS (13-May-2011 12:09)

 

A little test values:
<?php var_dump(strlen(null), strlen(123), strlen(-1), strlen('')); ?>

And the results are:
int(0) int(3) int(2) int(0)

Conclusion:
The values are converted to string before check the lenght.

 

canschi dot sergiu at yahoo dot com (08-Jan-2011 09:52)

 

Hello all, 

May I pos my firs  function as novice in php here . 
This funtion count all characters in a strign without spaces , so only chars, no spaces . 

<?php 
function countchar ($string) { 
    

$result strlen ($string)  -   substr_count($string' '); 
echo 
$result;  


countchar ($a); 
?> 

Hope to be useful for somebody !

 

basil at gohar dot us (08-Jun-2010 10:03)

 

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) == && !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.

 

Vladimir Zafirov (27-May-2009 05:28)

 

You can also just say:
<?php
  strlen
(utf8_decode($a))
?>
The utf8_decode($a) will take care of converting the utf characters that have more than one byte in to one symbol and the strlen() will count those correctly as length 1.

 

anto dot justus at gmail dot com (24-Apr-2009 04:14)

 

It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users.

<?php
function utf8_strlen($str)
    {
    
$count 0;

    for(
$i 0$i strlen($str); $i++)
        {
        
$value ord($str[$i]);
        if(
$value 127)
            {
            if(
$value >= 192 && $value <= 223)
                
$i++;
            elseif(
$value >= 224 && $value <= 239)
                
$i $i 2;
            elseif(
$value >= 240 && $value <= 247)
                
$i $i 3;
            else
                die(
'Not a UTF-8 compatible string');
            }
       
        
$count++;
        }
   
    return 
$count;
    }

?>

 

Amaroq (20-Mar-2009 07:51)

 

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.

 

Anonymous (16-Feb-2009 05:51)

 

simple speed test for UTF-8 strings:

<?php

header
("Content-type: text/html; charset=UTF-8");
ini_set('mbstring.internal_encoding''UTF-8');

?><pre><?

function utf8_strlen($s) {
    $c = strlen($s); $l = 0;
    for ($i = 0; $i < $c; ++$i) if ((ord($s[$i]) & 0xC0) != 0x80) ++$l;
    return $l;
}

function utf0_strlen($s) {
    $l = 0; $i = 0;
    while ($n = ord($s[$i++])) if (($n & 0xC0) != 0x80) ++$l;
    return $l;
}

function utfs_strlen($s) {
    $c = strlen($s);
    $l = 0;
    for($i = 0; $i < $c; $i++) {
        $v = ord($s[$i]);
        if($v > 127) {
            if($v >= 192 && $v <= 223) ++$i;
            elseif($v >= 224 && $v <= 239) $i += 2;
            elseif($v >= 240 && $v <= 247) $i += 3;
            else die('Not a UTF-8 compatible string');
        }
        ++$l;
    }
    return $l;


function spl_strlen($s) {
  return count(preg_split("//u", $s)) - 2;
}

function dcd_strlen($s) {
    return strlen(utf8_decode($s));


function preg_strlen($s) {
  return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $s, $d);
}

$src = '=123! !ы"в#$%&\'()*+,—./:;<=>?@[\]^_`{|}~'.
    '    йцукенгшщзхъфывапролджтьбю'.chr(0).'ы';

$tc = 10000; //test count

$l = mb_strlen($src, 'UTF-8'); //real testing string length

$lst = array('strlen', 'mb_strlen', 'dcd_strlen',
    'preg_strlen', 'utfs_strlen', 'utf8_strlen',
    'utf0_strlen', 'spl_strlen'); // list of functions

foreach ($lst as $f) {
    $t = microtime(1);
    for($i = 0; $i < $tc; $i++) $f($src);
    $t = microtime(1) - $t;
    printf("%14s : %0.6f : %03u%s\n", 
        $f, $t, $q = $f($src), $q != $l ? ' - failed!' : '');
}
?></pre>

main results:
        strlen : 0.009419 : 112 failed!
     mb_strlen : 0.016377 : 075
    dcd_strlen : 0.063055 : 075
   preg_strlen : 1.106809 : 075
   utfs_strlen : 1.701586 : 075
   utf8_strlen : 2.321344 : 075
   utf0_strlen : 2.578518 : 073 failed!
    spl_strlen : 3.789029 : 075

 

jonathan dot protzenko at gmail dot com (23-Aug-2008 03:35)

 

paolo dot mosna at gmail dot com's solution for getting the length of a unicode string didn't work for me. Instead, I used the following dirty function (which can be surely improved, but I'm giving the idea) :

<?php
function ustrlen($s) {
  
$a preg_split("//u"$s);
  
$i = -2;
  foreach (
$a as $b)
    
$i++;
  return 
$i;
}

?>

This will return the correct length for any unicode string.

 

radu_keepwalking at yahoo dot com (15-Apr-2008 12:37)

 

Another way to preview a text with or without html tags, and end not cut in a middle of a word.

<?php
function preview_text($TEXT$LIMIT$TAGS 0) {

    
// TRIM TEXT
    
$TEXT trim($TEXT);

    
// STRIP TAGS IF PREVIEW IS WITHOUT HTML
    
if ($TAGS == 0$TEXT preg_replace('/\s\s+/'' 'strip_tags($TEXT));

    
// IF STRLEN IS SMALLER THAN LIMIT RETURN
    
if (strlen($TEXT) < $LIMIT) return $TEXT;

    if (
$TAGS == 0) return substr($TEXT0$LIMIT) . " ...";
    else {

        
$COUNTER 0;
        for (
$i 0$i<= strlen($TEXT); $i++) {

            if (
$TEXT{$i} == "<"$STOP 1;

            if (
$STOP != 1) {

                
$COUNTER++;
            }

            if (
$TEXT{$i} == ">"$STOP 0;
            
$RETURN .= $TEXT{$i};

            if (
$COUNTER >= $LIMIT && $TEXT{$i} == " ") break;

        }

        return 
$RETURN "...";
    }

}

?>

 

mail4adry at inwind dot it (21-Aug-2007 09:53)

 

This can be useful to put a preview of an article on the front page when the rest of the article is displayed on another page: 

<?php 
function getPreviewText($text) { 
    
// Strip all tags 
    
$desc strip_tags(html_entity_decode($text), "<a><em>"); 
    
$charlen 0$crs 0
    if(
strlen_HTML($desc) == 0
        
$preview substr($desc069); 
    else 
    { 
        
$i 0
        while(
$charlen 80
        { 
            
$crs strpos($desc" "$crs)+1
            
$lastopen strrpos(substr($desc0$crs), "<"); 
            
$lastclose strrpos(substr($desc0$crs), ">"); 
            if(
$lastclose $lastopen
            { 
                
// we are not in a tag 
                
$preview substr($desc0$crs); 
                
$charlen strlen_noHTML($preview); 
            } 
            
$i++; 
        } 
    } 
    return 
$preview."&#8230;" 

?> 

will display text cut as near as possible to character 80 respecting each <a> and <em> tags and ending with ...

 

mail4adry at inwind dot it (21-Aug-2007 05:28)

 

<?php 
/** 
 * return length of a string regardeless of html tags in it 
 * 
 * @param string $html 
 * @return string 
 */ 

function strlen_noHtml($string){ 
    
$crs 0
    
$charlen 0
    
$len strlen($string); 
    while(
$crs $len
    { 
        
$offset $crs
        
$crs strpos($string"<"$offset); 
        if(
$crs === false
        { 
           
$crs $len
           
$charlen += $crs $offset
        } 
        else 
        { 
            
$charlen += $crs $offset
            
$crs strpos($string">"$crs)+1
        } 
    } 
    return 
$charlen


/** 
 * return length of a string regarding html tags in it 
 * 
 * @param string $html 
 * @return string 
 */ 

function strlen_Html($string){ 
    
$crs 0
    
$charlen 0
    
$len strlen($string); 
    while(
$crs $len
    { 
        
$scrs strpos($string"<"$crs); 
        if(
$scrs === false
        { 
           
$crs $len
        } 
        else 
        { 
            
$crs strpos($string">"$scrs)+1
            if(
$crs === false
                
$crs $len
            
$charlen += $crs $scrs
        } 
    } 
    return 
$charlen

?> 

Example: 

<?php 
$text 
"<p>Test 'a' paragraph.</p><!-- Comment --> Other text"

echo 
"strlen without HTML chars:".strlen_noHtml($text); 
echo 
"<br>"
echo 
"strlen of HTML chars:".strlen_html($text); 
?> 

Will output: 
strlen without HTML chars:30 
strlen of HTML chars:23

 

bradmwalker at cableone dot net (01-Jul-2007 11:48)

 

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 (27-Jun-2007 04:32)

 

<?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(014)); 

    
$t[] = array_combine(array(73,92,105,108,44), array_fill(055)); 
    
$t[] = array_combine(array(45,46,47,58,59,32), array_fill(065)); 
    
$t[] = array_combine(array(74,91,93,102,40,41), array_fill(066)); 
    
$t[] = array_combine(array(116), array_fill(017)); 
    
$t[] = array_combine(array(95,114,122,42), array_fill(048)); 
    
$t[] = array_combine(array(63,99,115,118,120,121), array_fill(069)); 
    
$t[] = array_combine(array(83,97,101,107), array_fill(0410)); 
    
$t[] = array_combine(array(111,48,49,50), array_fill(0410)); 
    
$t[] = array_combine(array(51,52,53,54,55,56,57,36), array_fill(0810)); 
    
$t[] = array_combine(array(70,75,76,80), array_fill(0411)); 
    
$t[] = array_combine(array(84,88,89,90,98), array_fill(0511)); 
    
$t[] = array_combine(array(100,103,104), array_fill(0311)); 
    
$t[] = array_combine(array(110,112,113,117), array_fill(0411)); 
    
$t[] = array_combine(array(65,195,135,66), array_fill(0412)); 
    
$t[] = array_combine(array(67,69,82,86), array_fill(0412)); 
    
$t[] = array_combine(array(78,79,81,85,94,43), array_fill(0613)); 
    
$t[] = array_combine(array(60,61,68,71,72), array_fill(0513)); 
    
$t[] = array_combine(array(119), array_fill(0114)); 
    
$t[] = array_combine(array(109), array_fill(0115)); 
    
$t[] = array_combine(array(64,77,87), array_fill(0316));   
   
    
// 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

 

paolo dot mosna at gmail dot com (10-Jan-2007 03:58)

 

Title: Strlen() ant bytes string lenght. 
Just to remember that strlen() return the number of characters of a string. Often the strlen() function is used to compute the length in bytes of a string. This is correct until string is single byte encoded. If multi-byte char-set is used this constraint i no more verified. So when you require the number of bytes of a ASCII or UTF-8 encoded string, it is better to use following function: 

<?php 
    
/** 
     * Count the number of bytes of a given string. 
     * Input string is expected to be ASCII or UTF-8 encoded. 
     * Warning: the function doesn't return the number of chars 
     * in the string, but the number of bytes. 
     * 
     * @param string $str The string to compute number of bytes 
     * 
     * @return The length in bytes of the given string. 
     */ 
    
function strBytes($str
    { 
      
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT 
      
      // Number of characters in string 
      
$strlen_var strlen($str); 
  
      
// string bytes counter 
      
$d 0
      
     
/* 
      * Iterate over every character in the string, 
      * escaping with a slash or encoding to UTF-8 where necessary 
      */ 
      
for ($c 0$c $strlen_var; ++$c) { 
          
          
$ord_var_c ord($str{$d}); 
          
          switch (
true) { 
              case ((
$ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): 
                  
// characters U-00000000 - U-0000007F (same as ASCII) 
                  
$d++; 
                  break; 
              
              case ((
$ord_var_c 0xE0) == 0xC0): 
                  
// characters U-00000080 - U-000007FF, mask 110XXXXX 
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 
                  
$d+=2
                  break; 
  
              case ((
$ord_var_c 0xF0) == 0xE0): 
                  
// characters U-00000800 - U-0000FFFF, mask 1110XXXX 
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 
                  
$d+=3
                  break; 
  
              case ((
$ord_var_c 0xF8) == 0xF0): 
                  
// characters U-00010000 - U-001FFFFF, mask 11110XXX 
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 
                  
$d+=4
                  break; 
  
              case ((
$ord_var_c 0xFC) == 0xF8): 
                  
// characters U-00200000 - U-03FFFFFF, mask 111110XX 
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 
                  
$d+=5
                  break; 
  
              case ((
$ord_var_c 0xFE) == 0xFC): 
                  
// characters U-04000000 - U-7FFFFFFF, mask 1111110X 
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 
                  
$d+=6
                  break; 
              default: 
                
$d++;    
          } 
      } 
      
      return 
$d
    } 

?> 

This function has been adapted form the JSON function used to convert character in UTF-8 representation. 

With this new function we solved problem in JSON and in PEAR/SOAP php libraries.

 

liquix at hjelpesentral dot no (17-Aug-2006 01:57)

 

An easy function to make sure the words in a sentence is not above the maximum lengt of characters. This is used to prevent that users posting for an example comments on your page and drag the page width out.

Returns true or false
<?php
function wordlength($txt$limit)
{
   
$words explode(' '$txt);

   foreach(
$words as $v)
   {
       if(
strlen($v) > $limit)
       {
            return 
false;
       }
   }

   return 
true;
}

?>

Uses like this:
<?php

$txt 
"Onelongword and some small ones";

if(!
wordlength($txt10))
{
    die(
"One of the words where too long");
}


?>

That will return false since one of the words in $txt is too long. (Maximum set to 10)

 

Hage Yaapa (12-Jan-2006 11:51)

 

Sometimes you really wanna make sure no user edits the 'maxlength' attribute of the HTML page and POSTs a 5 Mb string to your script. Probably, advanced programmers already take precautions, this one is just a very simple tip for beginners on how to check the character lenth of the POST variables in an effective manner.

<?php

// ALWAYS clean the POST variables of any HTML tags first.
// And here we do it in one easy step.
 
$_POST array_map('strip_tags'$_POST);
 

// These are the POST variables in the example
 
$alias $_POST['alias'];
 
$name $_POST['name'];
 
$status $_POST['status'];
 
$year $_POST['year'];
 

// We create an array that contains the expected character length
// for each POST variable
 
$exlen = array (
      
'alias'=>12,
      
'name'=>30,
      
'status'=>10,
      
'year'=>4
);
 

// Now check if any of them exceeds the expected length
 
foreach ($exlen as $key=>$val) {
      if (
strlen($$key) > $val) {
            
// The user has definitely edited the HTML! He has a lot of time, could be bad.
          // This section can edited according to your needs - very simple to complex.
          // Log the event or send an e-mail to the admin at the basic.
          // However, in this example we just print a warning.    
          
print 'WARNING: The FBI is looking for you, dude!';
          exit;
          
// The best part is that the script won't look for any other 
          // POST variables other than the ones which we are expecting already.
      
}
}

?>

Similarly, with the use of Regular Expressions you could check the data type and string format too.

 

bartek at proteus,pl (19-Jul-2005 01:08)

 

> 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

 

triadsebas at triads dot buildtolearn dot net (17-Jul-2005 01:49)

 

A nice use of the strlen() function, the following function will check if one of the words in $input is longer than $maxlenght,  $maxlenght is standard 40.
<?php
function check_input($input$maxlenght40)
$temp_array explode(" "$input);
foreach (
$temp_array as $word) {
if (
strlen($word) > $maxlenght) {
return 
false;
}
}
return 
true;

?>
Example:
<?php
if (!check_input($_POST['message'])) {
print 
'One of your words in your message in longer than 40 chars. Please edit your message.';
}

?>

 

http://nsk.wikinerds.org (22-Apr-2005 05:02)

 

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 (14-Mar-2005 03:07)

 

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.

 

php at capcarrere dot org (06-Feb-2005 02:32)

 

Hi, 

if you want to trim a sentence to a certain number of 
characters so that it is displayed nicely in a HTML page 
(in a table for instance), then you actually want to count 
the number of characters displayed rather than the 
actual number of characters of the string. 

For instance: 
"L&agrave; bas" should really be 5 character long, 
rather than 10. 

Also you don't want to cut a special char in the middle. 
For instance: 
If 3 is the maximum number of characters, 

"L&agrave; bas"  should be cut as "L&agrave; ..." 
and not "L&a..."; 

So here is a simple method to dothat: 

<?php 
function nicetrim ($s) { 
// limit the length of the given string to $MAX_LENGTH char 
// If it is more, it keeps the first $MAX_LENGTH-3 characters 
// and adds "..." 
// It counts HTML char such as &aacute; as 1 char. 
// 

  
$MAX_LENGTH 22
  
$str_to_count html_entity_decode($s); 
  if (
strlen($str_to_count) <= $MAX_LENGTH) { 
    return 
$s
  } 

  
$s2 substr($str_to_count0$MAX_LENGTH 3); 
  
$s2 .= "..."
  return 
htmlentities($s2); 

?>

 

chernyshevsky at hotmail dot com (05-Sep-2004 11:36)

 

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.

 

dtorop932 at hotmail dot com (03-Dec-2003 10:25)

 

To follow up on dr-strange's utf8_strlen(), here are two succinct alternate versions.  The first is slower for multibyte UTF-8, faster for single byte UTF-8.  The second should be much faster for all but very brief strings, and can easily live inline in code.  Neither validates the UTF-8.

Note that the right solution is to use mb_strlen() from the mbstring module, if one is lucky enough to have that compiled in...

<?php
// choice 1
function utf8_strlen($str) {
  
$count 0;
  for (
$i 0$i strlen($str); ++$i) {
    if ((
ord($str[$i]) & 0xC0) != 0x80) {
      ++
$count;
    }
  }
  return 
$count;
}


// choice 2
function utf8_strlen($str) {
  return 
preg_match_all('/[\x00-\x7F\xC0-\xFD]/'$str$dummy);
}

?>

 

Patrick (01-Aug-2003 10:36)

 

Just a general pointer that I have hit upon after some struggle:

Most blobs can easily be treated as strings, so to retreat info on a blob or to manipulate it in any way, I recommend trying out string-related functions first. They've worked well for me.

 

suchy at ecl dot pl (13-May-2003 11:22)

 

a little modification of rasmus solution 

<?php 
$tmp
=0$s="blah"
while(
$c=$s[$tmp++]) { echo $c; } 
?> 

but what happens when the string contains zeros? 

<?php $s="blah0blah"?> 
the script stops.... 

here is sample of code and the string is correcly parsed using strlen() even when containing zeros: 

<?php 
$s
="blah0blah"
$si=0
$s_len=strlen($s); 
for (
$si=0;$si<$s_len;$si++) 

 
$c=$s[$si]; 
 echo 
$c

?>

 

dr - strange at shaw dot ca (03-Oct-2002 03:08)

 

It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users. 

<?php 
function utf8_strlen($str
    { 
    
$count 0

    for(
$i 0$i strlen($str); $i++) 
        { 
        
$value ord($str[$i]); 
        if(
$value 127
            { 
            if(
$value >= 192 && $value <= 223
                
$i++; 
            elseif(
$value >= 224 && $value <= 239
                
$i $i 2
            elseif(
$value >= 240 && $value <= 247
                
$i $i 3
            else 
                die(
'Not a UTF-8 compatible string'); 
            } 
        
        
$count++; 
        } 
    
    return 
$count
    } 

?>

 

(26-May-2001 08:11)

 

Note that PHP does not need to traverse the string to know its length with strlen(). The length is an attribute of the array used to store the characters. Do not count on strings being terminated by a NULL character. This may not work with some character encodings, and PHP strings are binary-safe ! 
PHP4 included a NULL character after the last position in the string, however, this does not change the behavior of strlen or the binary safety: this NULL character is not stored. 

However PHP4 allows now to reference the position after the end of the string for both read and write access: 

* when reading at that position (e.g. $s[strlen($s)]), you get a warning with PHP3, and you'll get 0 with PHP4 not returning a warning. 

* you can assign it directly in PHP4 with one character to increase the string length by one character: 

<?php 
$s
[strlen($s)]=65//append 'A' 
$s[]=65//append 'A' 
$s[strlen($s)]=0//append NUL (stored!) 
$s[]=0//append NUL (stored!) 
?> 

Such code did not work in PHP3, where the only way to extend the string length was by using a concat operator. 

However, reading or writing past the end of the string, using an array index superior to the current string length will still raise a warning in PHP4.
来自 http://tools.dedecms.com/uploads/docs/php/function.strlen.html
普通分类: