1<?php
2
3require_once dirname(__FILE__)."/utf8_char2byte_pos.php";
4
5/**
6 * Returns a part of a UTF-8 string.
7 * Unit-tested by Kasper and works 100% like substr() / mb_substr() for full range of $start/$len
8 * (http://phpxref.com/xref/moodle/lib/typo3/class.t3lib_cs.php.source.html.gz)
9 *
10 * @param    string        UTF-8 string
11 * @param    integer        Start position (character position)
12 * @param    integer        Length (in characters)
13 * @return    string        The substring
14 * @see substr()
15 * @author    Martin Kutschker <martin.t.kutschker@blackbox.net>
16 */
17if (!function_exists('utf8_substr')) {
18  function utf8_substr($str,$start,$len=null)    {
19    if (!strcmp($len,'0'))    return '';
20
21    $byte_start = @utf8_char2byte_pos($str,$start);
22    if ($byte_start === false)    {
23      if ($start > 0)    {
24        return false;    // $start outside string length
25      } else {
26        $start = 0;
27      }
28    }
29
30    $str = substr($str,$byte_start);
31
32    if ($len!=null)    {
33      $byte_end = @utf8_char2byte_pos($str,$len);
34      if ($byte_end === false)    // $len outside actual string length
35        return $len<0 ? '' : $str;    // When length is less than zero and exceeds, then we return blank string.
36      else
37        return substr($str,0,$byte_end);
38    }
39    else    return $str;
40  }
41}
42
43?>