Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Created April 12, 2010 10:03
Show Gist options
  • Save wtnabe/363421 to your computer and use it in GitHub Desktop.
Save wtnabe/363421 to your computer and use it in GitHub Desktop.
A simple folding written in PHP for mainly Japanese
<?php
/**
* folding for mainly Japanese
*
* @license Two-clause BSD
*/
/**
* fold
*
* 全角半角表示を考慮して指定バイト数で文字列を桁折り。そのためいったん
* Shift_JIS に変換してから桁数を数える
*
* @since 2010-04-12
* @param string $str
* @param int $col
* @return string folded
*/
function fold( $str, $col = 78 ) {
return join( _split_with_sjis_bytes( $str, $col ), "\n" );
}
/**
* いわゆる半角の指定バイト数で文字列を分割
*
* @since 2010-04-12
* @param string $str
* @param int $col
* @return array
*/
function _split_with_sjis_bytes( $str, $col = 78 ) {
$lines = array();
while ( _bytes_as_sjis( $str ) > $col ) {
$last = null;
foreach ( range( floor( $col / 2 ), $col ) as $chars ) {
$substr = mb_substr( $str, 0, $chars );
if ( _bytes_as_sjis( $substr ) > $col ) {
break;
} else {
$last = $substr;
}
}
array_push( $lines, $last );
$str = mb_substr( $str, mb_strlen( $last ) );
}
if ( strlen( $str ) > 0 ) {
array_push( $lines, $str );
}
return $lines;
}
/**
* Shift_JISでのバイト数
*
* @since 2010-04-12
* @param string $str
* @return int
*/
function _bytes_as_sjis( $str ) {
return strlen( mb_convert_encoding( $str,
'sjis',
mb_internal_encoding() )
);
}
<?php
error_reporting( E_ALL ^ E_NOTICE );
mb_internal_encoding( 'utf-8' );
include_once( 'Pearified/Testing/SimpleTest/unit_tester.php' );
include_once( 'Pearified/Testing/SimpleTest/reporter.php' );
require_once( dirname( __FILE__ ).'/fold.php' );
class Test_Folding extends UnitTestCase {
function Test_Folding() {
}
function test_fold() {
$this->assertEqual( "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over th\ne lazy dog. The quick brown fox jumps over the lazy dog.",
fold( 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.' ) );
$this->assertEqual( "The quick brown fox jumps over the lazy dog. 日本語混ぜる。日本語が途中で折ら\nれるとどうなるの? The quick brown fox jumps over the lazy dog. The quick brow\nn fox jumps over the lazy dog.",
fold( "The quick brown fox jumps over the lazy dog. 日本語混ぜる。日本語が途中で折られるとどうなるの? The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog." )
);
}
}
if ( realpath( $_SERVER['SCRIPT_FILENAME'] ) == __FILE__ ) {
$test = new Test_Folding();
$reporter = null;
if ( SimpleReporter::inCli() ) {
$reporter = new TextReporter();
} else {
$reporter = new HtmlReporter();
}
$reporter->paintHeader( 'Test of fold.php' );
exit( $test->run( $reporter ) ? 0 : 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment