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 strlen
function to check the length of the string.
For instance, we write
$string = (strlen($string) > 13) ? substr($string, 0, 10) . '...' : $string;
to call strlen
with $string
to see if its length is bigger than 13.
If it is, we truncate the string with substr
by writing
substr($string, 0, 10) . '...'
Otherwise, we return $string
as is.
And we assign the result back to $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 strlen
function to check the length of the string.