PHP Tutorial - PHP strlen() Function






Definition

The strlen() function takes a string and returns the number of characters in it.

Syntax

PHP strlen() Function has the following syntax.

int strlen ( string str )

Parameter

str is the string value to check.

Return

PHP strlen() Function returns the length of a string.

Example

Get the string length


<?PHP
print strlen("Foo") . "\n"; 
print strlen("Hi from java2s.com!") . "\n"; 
?>

For multibyte strings we should be measured with mb_strlen().

The code above generates the following result.





Example 2

The following code shows how to display dot if the string is too long.


<?php// www  . ja v a2 s .co  m
   // Limit $summary to how many characters?
   $limit = 10;

$summary = <<< summary
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
this is a test from java2s.com
summary;

   if (strlen($summary) > $limit) 
      $summary = substr($summary, 0, strrpos(substr($summary, 0, $limit), ' ')) . '...';
   echo $summary;
?>

The code above generates the following result.





Example 3

The following code shows how to emulate str_pad() with while loop and strlen function.


//www  .j a  v a  2s  .  c o  m
<!DOCTYPE html>
<html>
  <body>
    <h1></h1>

    <?php
    
    $myString = "Hello, world!";
    $desiredLength = 20;
    
    echo "<pre>Original string: '$myString'</pre>";
    
    while ( strlen( $myString ) < 20 ) {
      $myString .= " ";
    }
    
    echo "<pre>Padded string:   '$myString'</pre>";
    ?>

  </body>
</html>

The code above generates the following result.