The strlen() function takes a string and returns the number of characters in it.
PHP strlen() Function has the following syntax.
int strlen ( string str )
str
is the string value to check.
PHP strlen() Function returns the length of a string.
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.
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.
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.