There are a number of examples of this in the user comments on substr() function
One of the simpler ones is:
function wrapTrunc($str, $len) {
return substr(($str=wordwrap($myvar,$len,'$$')),0,strpos($str,'$$'));
}
A major disadvantage of this wordwrap
-based approach is you waste time and memory wrapping the whole string, even though you only need to keep the first $len
chars.
Here's a regex-based solution I just whipped up that I'm a little more comfortable with:
<?php
$myvar = 'this is my custom text, it is a very long text so be patiente, take care!';
var_dump(trunc($myvar, 50));
function trunc($str, $len = 50) {
return preg_replace("/^(.{1,$len}\S)\b.*/", '$1', $str);
}
Sample output:
$ php test.php
string(49) "this is my custom text, it is a very long text so"