Back to Crypt class

Method safeSubstr

public static string
safeSubstr
(mixed $str, mixed $start, mixed $length = null)
Safely extract a substring
Parameters
  • string $str The string to extract the substring from
  • int $start The starting position to extract from
  • int $length The length of the string to return
Returns
  • string
Since
  • 3.5
Class: Crypt
Project: Joomla

Method safeSubstr - Source code

/**
 * Safely extract a substring
 *
 * This method is derived from \ParagonIE\Halite\Util::safeSubstr()
 *
 * @param   string   $str     The string to extract the substring from
 * @param   integer  $start   The starting position to extract from
 * @param   integer  $length  The length of the string to return
 *
 * @return  string
 *
 * @since   3.5
 */
public static function safeSubstr($str, $start, $length = null)
{
    static $exists = null;
    if ($exists === null) {
        $exists = \function_exists('mb_substr');
    }
    if ($exists) {
        // In PHP 5.3 mb_substr($str, 0, NULL, '8bit') returns an empty string, so we have to find the length ourselves.
        if ($length === null) {
            if ($start >= 0) {
                $length = static::safeStrlen($str) - $start;
            } else {
                $length = -$start;
            }
        }
        return mb_substr($str, $start, $length, '8bit');
    }
    // Unlike mb_substr(), substr() doesn't accept NULL for length
    if ($length !== null) {
        return substr($str, $start, $length);
    }
    return substr($str, $start);
}