Sometimes, we want to truncate a string to the first n characters of a string and add three dots if any characters are removed with PHP.
In this article, we’ll look at how to truncate a string to the first n characters of a string and add three dots if any characters are removed with PHP.
How to truncate a string to the first n characters of a string and add three dots if any characters are removed with PHP?
To truncate a string to the first n characters of a string and add three dots if any characters are removed with PHP, we can use the substr
function.
For instance, we write
$string = strlen($string) > 13 ? substr($string, 0, 10) . "..." : $string;
to call substr
with $string
to return a new string that has the characters in $string
from index 0 to 9.
We return the string returned by substr
if the $string
‘s length is bigger than 13.
We get the length of $string
with strlen
.
Otherwise, we return $string
.
Conclusion
To truncate a string to the first n characters of a string and add three dots if any characters are removed with PHP, we can use the substr
function.