Skip to content

Instantly share code, notes, and snippets.

@ayumu83s
Created May 16, 2014 04:53
Show Gist options
  • Save ayumu83s/95976cae164489767801 to your computer and use it in GitHub Desktop.
Save ayumu83s/95976cae164489767801 to your computer and use it in GitHub Desktop.
use utf8;
use strict;
use warnings;
use Encode 'encode_utf8';
# 文字が指定のバイト数を超えている場合に切り取る。
sub kirisute_gomen {
my ($string, $byte_len, $str_len) = @_;
return $string if (length(encode_utf8($string)) <= $byte_len && length($string) <= $str_len);
# 指定の文字数まで切り取って、byte超えてたら1文字ずづ捨てていく作戦
my $result = substr($string, 0, $str_len);
while (length(encode_utf8($result)) > $byte_len || length($result) > $str_len) {
$result = substr($result, 0, -1);
}
return $result;
}
=pod
# 5文字(10byte)制限のテスト
kirisute_gomen('あいうえお', 10, 5); # あいう 9byte
kirisute_gomen('あいueお', 10, 5); # あいue 8byte
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment