Created
February 11, 2011 02:43
-
-
Save Cside/821841 to your computer and use it in GitHub Desktop.
全角・半角混じった文字をいい感じにsubstrする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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