|
|
 |
strlen (PHP 3, PHP 4, PHP 5) strlen -- Get string length Descriptionint strlen ( string string )
Returns the length of the given string.
Example 1. A strlen() example |
<?php
$str = 'abcdef';
echo strlen($str); $str = ' ab cd ';
echo strlen($str); ?>
|
|
See also count(), and mb_strlen().
User Contributed Notes
strlen
http://nsk.wikinerds.org
22-Apr-2005 11: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 09: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 08: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à 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à bas" should be cut as "Là ..."
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 á 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);
}
corey at eyewantmedia dot com
27-Jan-2005 05:32
Note on the FilePop. It should be modified stlightly so as not to throw a warning:
function FilePop($filename, $terminator="\n") {
if (file_exists($filename)) {
$oldStuff = file_get_contents($filename); //get those file contents
$pos = strpos($oldStuff, $terminator); // find our first terminator
if ($pos == false) { //No terminator detected. Is there one item or no items?
if (strlen($oldStuff) < 1) { // There is nothing!
$result = false;
} else { //There is only one thing!
$result = $oldStuff; //store that thing
file_put_contents ( $filename, ''); //pop it out of file
}
} else { //There are many things, and we found the first one
$result = substr($oldStuff, 0, $pos); //get the first thing
file_put_contents ( $filename, substr($oldStuff, ($pos + strlen($terminator))) ); //re-put everything but the popped item in the file.
}
} else {
$result = false;
}
return $result; //return whatever happened
}
corey at eyewantmedia dot com
27-Jan-2005 03:39
I found that I needed something a little beyond array pushing and popping so I could share a stack between calls to a script. I wrote these quick functions, and while they are not all that efficient, they are certainly better than hitting a database server to manage a stack between script calls. Anyway, here we go.
function FilePush($filename, $thingToPush, $terminator="\n") {
$oldStuff = file_get_contents($filename); //Get the old file
$result = file_put_contents ( $filename, $thingToPush . $terminator . $oldStuff ); //add the new stuff to the old and write it
return $result; //return whatever file_put_contents says
}
function FilePop($filename, $terminator="\n") {
$oldStuff = file_get_contents($filename); //get those file contents
$pos = strpos($oldStuff, $terminator); // find our first terminator
if ($pos == false) { //No terminator detected. Is there one item or no items?
if (strlen($oldStuff) < 1) { // There is nothing!
$result = false;
} else { //There is only one thing!
$result = $oldStuff; //store that thing
file_put_contents ( $filename, ''); //pop it out of file
}
} else { //There are many things, and we found the first one
$result = substr($oldStuff, 0, $pos); //get the first thing
file_put_contents ( $filename, substr($oldStuff, ($pos + strlen($terminator))) ); //re-put everything but the popped item in the file.
}
return $result; //return whatever happened
}
webmaster at elcurriculum dot com
08-Jan-2005 01:49
This function is for cut the long text.
//Recortar texto si es mayor de $Car caracteres...
function GetRecortarTexto ($vTxt, $Car) {
if (strlen($vTxt) > $Car) {
return substr($vTxt, 0, $Car) . "...";
} else return $vTxt;
}
//Example
$frase = "This is a long text";
$char = 10; //Max long...
echo GetRecortarTexto($frase, $char);
Return:
This is a ...
More:
http://php.elcurriculum.com
http://tryke.elcurriculum.com
Patrick(a)Bierans()de
29-Nov-2004 05: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
05-Sep-2004 05: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 02:03
A more succinct way to get strlen of UTF-8 string w/out the multi-byte string library:
$len = preg_match_all('/./u', $str, $dummy);
A side effect is the $dummy contains a UTF-8 character by character breakdown of the string...
dtorop932 at hotmail dot com
03-Dec-2003 04: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
function utf8_strlen($str) {
$count = 0;
for ($i = 0; $i < strlen($str); ++$i) {
if ((ord($str[$i]) & 0xC0) != 0x80) {
++$count;
}
}
return $count;
}
function utf8_strlen($str) {
return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $dummy);
}
?>
25-Sep-2003 08:13
> 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....
Then use this:
<?php
$tmp=0; $s="blah0blah";
while( ord($c = $s[$tmp++]) )
echo $c;
?>
Patrick
01-Aug-2003 04: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 05: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;
}
?>
alber at netdot dot ch
28-Jan-2003 07:26
If you are using php < 4.01 this function makes the same as
str_pad in php >=4.01
function str_pad($variable, $size)
{
while (strlen($variable) < $size)
{
$variable = $variable ." "; //Add Space
}//End While
return $variable;
}//End Function
ex.
$NameVorname = "AlberMichael";
$name=substr(str_pad($NameVorname,20),0,20);
$pdf=str_replace("NameVorname",$name,$pdf);
echo $pdf; //Returns AlberMichael
dr - strange at shaw dot ca
02-Oct-2002 09: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;
}
26-May-2001 02: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 12: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
15-Mar-2001 07: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
03-Nov-2000 01: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.
| |