strlen

(PHP 3, PHP 4, PHP 5)

strlen -- Get string length

Description

int strlen ( string string )

Returns the length of the given string.

例子 1. A strlen() example

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

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

See also count(), and mb_strlen().


add a note add a note User Contributed Notes
liquix at hjelpesentral dot no
17-Aug-2006 08: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($txt, 10))
{
   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)
abraao dot zaidan at uol dot com dot br
19-Jul-2006 06:15
I make a function like strlen():

<?php
function contaci($string, $inc)
{
$item = substr($string, $inc, 1);
if(
$item != "")
{
$inc++;
$volta = contaci($string, $inc);
return
$volta;
}
else
{
return
$inc;
}
}
function
conta($string)
{
$volta = contaci($string, 0);
return
$volta;
}

$string = "abcdef";
$conta = conta($string); // ==> 6

$string = " ab cd ";
$conta = conta($string); // ==> 7

?>
Hage Yaapa
12-Jan-2006 07: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.
anpaza at mail dot ru
01-Dec-2005 04:58
Here's a better strlen() for UTF-8 strings that doesn't access the byte past end of the string (on which newer PHP barfs):

function strlen_utf8 ($str)
{
   $i = 0;
   $count = 0;
   $len = strlen ($str);
   while ($i < $len)
   {
   $chr = ord ($str[$i]);
   $count++;
   $i++;
   if ($i >= $len)
       break;

   if ($chr & 0x80)
   {
       $chr <<= 1;
       while ($chr & 0x80)
       {
       $i++;
       $chr <<= 1;
       }
   }
   }
   return $count;
}
bartek at proteus,pl
19-Jul-2005 08: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):

$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 08: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, $maxlenght= 40)
$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
23-Apr-2005 12:02
Beware: strlen() counts new line characters at the end of a string, too!

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

The above code will output 4.
packe100 at hotmail dot com
14-Mar-2005 11: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 10: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:

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_count, 0, $MAX_LENGTH - 3);
  $s2 .= "...";
  return htmlentities($s2);
}
Patrick(a)Bierans()de
29-Nov-2004 07:24
function array_strlen(&$array,$fuse=200,$depth=0)
{
  // returns the strlen of all elements in a given array, an array inside
  // an array will add another 8 points

  // fuse: Recursion is limited to 200 calls, if you want unlimited calls
  //      use fuse=0 - warning: if an array element contains a reference
  //      to the array itself it will run endless if fuse set to 0 or below.

  $strlen=0;
  $fuse-=1;
  if ($fuse==0) return $strlen;

  if (is_array($array))
  {
   if ($depth>0) $strlen+=8;
   reset($array);
   $depth+=1;
   foreach ($array as $sub) $strlen+=array_strlen($sub,$fuse,$depth);
  }
  else
  {
   $strlen+=strlen($array);
  }
  return $strlen;
} // array_strlen()
chernyshevsky at hotmail dot com
06-Sep-2004 06:36
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

$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
04-Dec-2003 06: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
02-Aug-2003 05: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 06:22
a little modification of rasmus solution

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

but what happens when the string contains zeros?
$s="blah0blah";
the script stops....

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

<?
$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 10: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.

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;
   }
27-May-2001 03: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:

$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.
ben at _idataconnect dot com
01-Apr-2001 02:44
I think another thing that people aren't understanding about this is that PHP doesn't use pointers like C. The way you can treat string variables as arrays seems to be added for convenience. Like someone posted earlier, you shouldn't rely on the language to hit an error and end the loop. If you do things like that and someone changed the way PHP (or any language) worked with those kind of errors, your program just might not work anymore.
validus at c-gate dot net
16-Mar-2001 09:07
Several people here have commented on
the termination of strings in PHP with the NULL character.
My tests have shown that

PHP3 does NOT terminate strings
PHP4 DOES terminate with a NULL   
  character. 

And one of the previous posters seemed to indicate that zero couldn't be a part of a string if it were NULL terminated.  It can.  A zero is ASCII 48
and a NULL character is ASCII 0.

cheers
validus
rasmus at php dot net
04-Nov-2000 03:37
This bit of code works just fine in PHP:

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

Depending on your warning level you may get a warning when $tmp = 4 because you have gone beyond the end of the string.  If you don't care about this warning either change your warning level or simply swallow it using:

  $tmp=0; $s="blah";
  while(@$c=$s[$tmp++]) { echo $c; }

The @ in front of the assignment will swallow any warnings from that assignment.