To truncate a string variable in php, the easiest way is to use the php substr() function.
$variable = "this is a variable";
$truncated = substr($variable,0,6);
echo $truncated;
//Output:
this i
Another way to truncate a string is with the mb_strimwidth() function.
$variable = "this is a variable";
$truncated = mb_strimwidth($variable,0,6);
echo $truncated;
//Output:
this i
When working with string variables in our php programs, it is useful to be able to easily manipulate and change the value of the variables.
One such change is if you want to truncate a string and remove characters from the end.
To truncate a string in php, you can use the substr() function.
substr() takes three arguments (a string, a start position, and an ending position), and returns a substring of the given string.
To remove characters from the end of a string, you can use substr() by starting at 0 and ending at the position of the character you want to end your string at.
Below is an example of how to use substr() to truncate a string in php.
$variable = "this is a variable";
$truncated = substr($variable,0,6);
echo $truncated;
//Output:
this i
Truncating a String with mb_strimwidth() in php
Another way you can get a truncated string of a specified width is with the mb_strimwidth() function.
mb_strimwidth() takes in a string, starting position and ending position and returns a substring of the given string.
The one difference between substr() and mb_strimwidth() is you can pass one more parameter, ‘trim_marker’, which will concatenate given string after getting the substring.
Below is a simple example in php of how to truncate a string with mb_strimwidth().
$variable = "this is a variable";
$truncated = mb_strimwidth($variable,0,6, "...");
echo $truncated;
//Output:
this i...
Hopefully this article has been useful for you to learn how to truncate string variables in php.