Файл: adultscript-2.0.3-pro/files/libraries/framework/multibyte/substr.php
Строк: 77
<?php
defined('_VALID') or die('Restricted Access!');
function _utf8_substr($str, $offset, $length = NULL)
{
$str = (string)$str;
$offset = (int)$offset;
if (!is_null($length)) $length = (int)$length;
// handle trivial cases
if ($length === 0) return '';
if ($offset < 0 && $length < 0 && $length < $offset)
return '';
// normalise negative offsets (we could use a tail
// anchored pattern, but they are horribly slow!)
if ($offset < 0) {
// see notes
$strlen = strlen(utf8_decode($str));
$offset = $strlen + $offset;
if ($offset < 0) $offset = 0;
}
$Op = '';
$Lp = '';
// establish a pattern for offset, a
// non-captured group equal in length to offset
if ($offset > 0) {
$Ox = (int)($offset/65535);
$Oy = $offset%65535;
if ($Ox) {
$Op = '(?:.{65535}){'.$Ox.'}';
}
$Op = '^(?:'.$Op.'.{'.$Oy.'})';
} else {
// offset == 0; just anchor the pattern
$Op = '^';
}
// establish a pattern for length
if (is_null($length)) {
// the rest of the string
$Lp = '(.*)$';
} else {
if (!isset($strlen)) {
// see notes
$strlen = strlen(utf8_decode($str));
}
// another trivial case
if ($offset > $strlen) return '';
if ($length > 0) {
// reduce any length that would
// go passed the end of the string
$length = min($strlen-$offset, $length);
$Lx = (int)( $length / 65535 );
$Ly = $length % 65535;
// negative length requires a captured group
// of length characters
if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}';
$Lp = '('.$Lp.'.{'.$Ly.'})';
} else if ($length < 0) {
if ( $length < ($offset - $strlen) ) {
return '';
}
$Lx = (int)((-$length)/65535);
$Ly = (-$length)%65535;
// negative length requires ... capture everything
// except a group of -length characters
// anchored at the tail-end of the string
if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}';
$Lp = '(.*)(?:'.$Lp.'.{'.$Ly.'})$';
}
}
if (!preg_match( '#'.$Op.$Lp.'#us',$str, $match )) {
return '';
}
return $match['1'];
}
?>