Created
December 22, 2011 04:37
-
-
Save kijtra/1508930 to your computer and use it in GitHub Desktop.
[PHP] 文章において、一行の長さ(日本語は2バイト計算)を制限し自動改行する関数。さらにインデントも可能(一行の長さはインデントも含めた長さになる)。メルマガなどに。
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
<?php | |
function str_wordwrap($str,$max=NULL,$indent=NULL,$firstindent=true,$charset='utf8'){ | |
$max=(empty($max) ? 74 : (($max%2==0) ? $max-1 : $max)); | |
$str=str_replace("\r\n","\n",$str); | |
$sindent=mb_convert_encoding($indent,'sjis',$charset); | |
$ilen=(!empty($indent)) ? strlen($sindent) : 0; | |
$arr=array(); | |
$out=NULL; | |
foreach(explode("\n",$str) as $line){ | |
if(strpos($line,'http')===0){ | |
$out.=$line."\n"; | |
continue; | |
}else if(empty($line)){ | |
$out.=$indent."\n"; | |
continue; | |
} | |
$sjis=mb_convert_encoding(trim($line),'sjis',$charset); | |
$len=strlen($sjis); | |
if($len>$max-$ilen){ | |
$ret=NULL; | |
if(preg_match_all('/((https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+))/',$sjis,$m)){ | |
foreach($m[1] as $v){ | |
$ret.="{$v}\n"; | |
$sjis=str_replace($v,'',$sjis); | |
} | |
}else if(preg_match("/([a-zA-Z0-9\._\-\@\+]+){2,}$/",$sjis,$m)){ | |
$ret.=$m[1]."\n"; | |
$sjis=str_replace($m[1],'',$sjis); | |
} | |
$p=$sindent; | |
foreach(range(0,mb_strlen($sjis,'sjis')) as $v){ | |
$s=mb_substr($sjis,$v,1,'sjis'); | |
if(strlen($p)>=$max-1){ | |
$out.=mb_convert_encoding($p,$charset,'sjis')."\n"; | |
$p=$sindent; | |
} | |
$p.=$s; | |
} | |
if($p!=$sindent){ | |
$out.=mb_convert_encoding($p,$charset,'sjis')."\n"; | |
} | |
if(!empty($ret)){ | |
$out.=$indent.$ret; | |
} | |
}else{ | |
$out.=$indent.$line."\n"; | |
} | |
} | |
if(!$firstindent){ | |
$out=preg_replace('#^'.$indent.'#u','',$out); | |
} | |
return $out; | |
} | |
/* | |
例) | |
$str="あいうえおかきくけこさしす"; | |
echo str_wordwrap($str,5); | |
↓ | |
あいうえお | |
かきくけこ | |
さしす | |
$str="あいうえおかきくけこさしす"; | |
echo str_wordwrap($str,10,'---'); | |
↓ | |
---あいう | |
---えお | |
---かきく | |
---けこ | |
---さしす | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment