Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Shorten string with a "..." body in PHP?
In PHP, you can shorten long strings by adding "..." in the middle while preserving the beginning and end portions. This technique is useful for displaying truncated text while keeping important parts visible.
Basic String Shortening
Here's how to shorten a string when it exceeds a certain length ?
<?php
$sentence = "This is my first PHP program";
if (strlen($sentence) >= 13) {
echo substr($sentence, 0, 20) . " ... " . substr($sentence, -4);
} else {
echo $sentence;
}
?>
This is my first PHP ... gram
Flexible Function Approach
Create a reusable function to shorten any string ?
<?php
function shortenString($text, $maxLength = 20, $startChars = 10, $endChars = 4) {
if (strlen($text) <= $maxLength) {
return $text;
}
return substr($text, 0, $startChars) . " ... " . substr($text, -$endChars);
}
// Example usage
$longText = "This is a very long sentence that needs to be shortened";
echo shortenString($longText, 25, 12, 6);
echo "<br>";
echo shortenString("Short text");
?>
This is a ve ... ened Short text
Parameters Explanation
| Parameter | Purpose | Example |
|---|---|---|
$text |
Original string | "Long sentence here" |
$maxLength |
Threshold for shortening | 20 |
$startChars |
Characters to keep from start | 10 |
$endChars |
Characters to keep from end | 4 |
Conclusion
Use substr() with strlen() to create shortened strings with ellipsis. The flexible function approach allows customization of the truncation parameters for different use cases.
Advertisements
