Skip to content

Instantly share code, notes, and snippets.

@Cside
Created February 11, 2011 02:43
Show Gist options
  • Save Cside/821841 to your computer and use it in GitHub Desktop.
Save Cside/821841 to your computer and use it in GitHub Desktop.
全角・半角混じった文字をいい感じにsubstrする
use utf8;
use Encode qw/encode_utf8/;
sub truncates {
my ($str, $size, $suffix) = @_;
$str = '' unless $str;
$size = 32 unless $size;
$suffix = "..." unless $suffix;
my $b = 0;
for (my $i = 0; $i < length $str; $i++) {
$b += length(encode_utf8 substr($str, $i, 1)) == 1 ? 1 : 2;
if ($b > $size) {
return substr($str, 0, $i) . $suffix;
}
}
$str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment