/** * Modifier plugin : count the number of characters in a text * * <pre>{$mytext|count_characters} * {$mytext|count_characters:true}</pre> * @param string $string * @param boolean $include_spaces include whitespace in the character count * @return integer */ function jtpl_modifier_common_count_characters($string, $include_spaces = false) { if ($include_spaces) { return iconv_strlen($string, jTpl::getEncoding()); } return preg_match_all("/[^\\s]/", $string, $match); }
/** * @covers Symfony\Polyfill\Iconv\Iconv::iconv_strlen * @covers Symfony\Polyfill\Iconv\Iconv::strlen1 * @covers Symfony\Polyfill\Iconv\Iconv::strlen2 */ public function testIconvStrlen() { $this->assertSame(4, iconv_strlen('déjà', 'UTF-8')); $this->assertSame(3, iconv_strlen('한국어', 'UTF-8')); $this->assertSame(4, p::strlen2('déjà')); $this->assertSame(3, p::strlen2('한국어')); }
/** * Convert a string to ASCII * * @access public * @param string $str The string to convert * @param string $charset The default charset to use * @return string The converted string */ public static function toASCII($str, $charset = 'UTF-8') { $asciistr = ''; if (mb_detect_encoding($str, 'UTF-8', true) === false) { $str = utf8_encode($str); } if (version_compare(PHP_VERSION, '5.6.0') < 0) { iconv_set_encoding('input_encoding', 'UTF-8'); iconv_set_encoding('internal_encoding', 'UTF-8'); iconv_set_encoding('output_encoding', $charset); } $str = html_entity_decode($str, ENT_QUOTES, $charset); $strlen = iconv_strlen($str, $charset); for ($i = 0; $i < $strlen; $i++) { $char = iconv_substr($str, $i, 1, $charset); if (!preg_match('/[`\'^~"]+/', $char)) { if ('UTF-8' === $charset) { $asciistr .= preg_replace('/[`\'^~"]+/', '', iconv($charset, 'ASCII//TRANSLIT//IGNORE', $char)); } else { $asciistr .= preg_replace('/[`\'^~"]+/', '', iconv('UTF-8', $charset . '//TRANSLIT//IGNORE', $char)); } } else { $asciistr .= $char; } } return $asciistr; }
/** * Filter: removes unnecessary whitespace and shortens value to control's max length. * @return string */ public function sanitize($value) { if ($this->control->maxlength && iconv_strlen($value, 'UTF-8') > $this->control->maxlength) { $value = iconv_substr($value, 0, $this->control->maxlength, 'UTF-8'); } return String::trim(strtr($value, "\r\n", ' ')); }
public function truncate($string, $length = 50, $chars = true, $postfix = '...') { $truncated = trim($string); if (!$string) { return $truncated; } $length = (int) $length; if ($chars) { $fullLength = iconv_strlen($truncated, 'UTF-8'); if ($fullLength > $length) { $truncated = trim(iconv_substr($truncated, 0, $length, 'UTF-8')) . $postfix; } // words } else { $truncated = str_replace(' ', ' ', $truncated); $words = explode(' ', $truncated); $truncated = ''; $count = count($words); for ($i = 0; $i < $count; $i++) { $truncated .= $words[$i] . ' '; if ($length == $i) { $truncated .= $postfix; break; } } } return $truncated; }
public function login() { $email = strtolower($this->getParam('email')); $password = $this->getParam('password'); $remember = $this->getParam('remember'); if (!$email || !$password) { exit(json_encode(['result' => 'fail', 'message' => 'Все поля формы обязательны для заполнения'])); } // if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // exit(json_encode(['result' => 'fail', 'message' => 'Некорректный Email-адрес'])); // } if (iconv_strlen($password) < Registry::get('min_password_length') || iconv_strlen($password) > Registry::get('max_password_length')) { exit(json_encode(['result' => 'fail', 'message' => 'Длина пароля должна быть в пределах от ' . Registry::get('min_password_length') . ' до ' . Registry::get('max_password_length') . ' символов'])); } $user = DB::run()->query("select * from users where email = '{$email}'")->fetch(); if (!$user) { exit(json_encode(['result' => 'fail', 'message' => 'Данный Email-адрес в системе не зарегистрирован'])); } $userPassHash = Tools::hash($password, Registry::get('hash_salt')); if ($user->password != $userPassHash) { exit(json_encode(['result' => 'fail', 'message' => 'Неверный пароль'])); } if ($remember === 'true') { Tools::setUserAuth($user, true); } else { Tools::setUserAuth($user); } exit(json_encode(['result' => 'done', 'message' => 'Успешный вход в систему!<br>Сейчас Вы будете перенаправлены.'])); }
public function cstr($text, $start = 0, $limit = 12) { if (function_exists('mb_substr')) { $more = mb_strlen($text) > $limit ? TRUE : FALSE; $text = mb_substr($text, 0, $limit, 'UTF-8'); return array($text, $more); } elseif (function_exists('iconv_substr')) { $more = iconv_strlen($text) > $limit ? TRUE : FALSE; $text = iconv_substr($text, 0, $limit, 'UTF-8'); return array($text, $more); } else { preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf]\r\n \t\t[x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]\r\n \t\t|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $text, $ar); if (func_num_args() >= 3) { if (count($ar[0]) > $limit) { $more = TRUE; $text = join("", array_slice($ar[0], 0, $limit)); } $more = TRUE; $text = join("", array_slice($ar[0], 0, $limit)); } else { $more = FALSE; $text = join("", array_slice($ar[0], 0)); } return array($text, $more); } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof Length) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Length'); } if (null === $value || '' === $value) { return; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $stringValue = (string) $value; if ('UTF8' === ($charset = strtoupper($constraint->charset))) { $charset = 'UTF-8'; // iconv on Windows requires "UTF-8" instead of "UTF8" } $length = @iconv_strlen($stringValue, $charset); $invalidCharset = false === $length; if ($invalidCharset) { $this->context->buildViolation($constraint->charsetMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ charset }}', $constraint->charset)->setInvalidValue($value)->setCode(Length::INVALID_CHARACTERS_ERROR)->addViolation(); return; } if (null !== $constraint->max && $length > $constraint->max) { $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->max)->setInvalidValue($value)->setPlural((int) $constraint->max)->setCode(Length::TOO_LONG_ERROR)->addViolation(); return; } if (null !== $constraint->min && $length < $constraint->min) { $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->min)->setInvalidValue($value)->setPlural((int) $constraint->min)->setCode(Length::TOO_SHORT_ERROR)->addViolation(); } }
/** * 字符串截取,支持中文和其他编码 * @static * @access public * @param string $str 需要转换的字符串 * @param string $start 开始位置 * @param string $length 截取长度 * @param string $charset 编码格式 * @param string $suffix 截断显示字符 * @return string */ function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = '...') { $total = 0; if (function_exists("mb_substr")) { $total = mb_strlen($str, $charset); if ($total <= $length) { return $str; } $slice = mb_substr($str, $start, $length, $charset); } elseif (function_exists('iconv_substr')) { $total = iconv_strlen($str, $charset); if ($total <= $length) { return $str; } $slice = iconv_substr($str, $start, $length, $charset); if (false === $slice) { $slice = ''; } } else { $re['utf-8'] = "/[-]|[�-�][�-�]|[�-�][�-�]{2}|[�-�][�-�]{3}/"; $re['gb2312'] = "/[-]|[�-�][�-�]/"; $re['gbk'] = "/[-]|[�-�][@-�]/"; $re['big5'] = "/[-]|[�-�]([@-~]|�-�])/"; preg_match_all($re[$charset], $str, $match); $total = count($match[0]); if ($total <= $length) { return $str; } $slice = join("", array_slice($match[0], $start, $length)); } return $suffix ? $slice . $suffix : $slice; }
function mb_strlen($str, $enc = FALSE) { if (function_exists('iconv_strlen')) { return $enc ? iconv_strlen($str, $enc) : iconv_strlen($str); } return strlen($str); }
/** * String padding * * @param string $input * @param integer $padLength * @param string $padString * @param integer $padType * @param string $charset * @return string */ public static function strPad($input, $padLength, $padString = ' ', $padType = STR_PAD_RIGHT, $charset = 'UTF-8') { $return = ''; $lengthOfPadding = $padLength - iconv_strlen($input, $charset); $padStringLength = iconv_strlen($padString, $charset); if ($padStringLength === 0 || $lengthOfPadding === 0) { $return = $input; } else { $repeatCount = floor($lengthOfPadding / $padStringLength); if ($padType === STR_PAD_BOTH) { $lastStringLeft = ''; $lastStringRight = ''; $repeatCountLeft = $repeatCountRight = ($repeatCount - $repeatCount % 2) / 2; $lastStringLength = $lengthOfPadding - 2 * $repeatCountLeft * $padStringLength; $lastStringLeftLength = $lastStringRightLength = floor($lastStringLength / 2); $lastStringRightLength += $lastStringLength % 2; $lastStringLeft = iconv_substr($padString, 0, $lastStringLeftLength, $charset); $lastStringRight = iconv_substr($padString, 0, $lastStringRightLength, $charset); $return = str_repeat($padString, $repeatCountLeft) . $lastStringLeft . $input . str_repeat($padString, $repeatCountRight) . $lastStringRight; } else { $lastString = iconv_substr($padString, 0, $lengthOfPadding % $padStringLength, $charset); if ($padType === STR_PAD_LEFT) { $return = str_repeat($padString, $repeatCount) . $lastString . $input; } else { $return = $input . str_repeat($padString, $repeatCount) . $lastString; } } } return $return; }
public static function Len($str) { if (function_exists('mb_strlen')) { $count = mb_strlen($str, __CFG::CHARSET); } else { if (function_exists('iconv_strlen')) { $count = iconv_strlen($str, __CFG::CHARSET); } else { if (strtolower(__CFG::CHARSET) == 'utf-8') { $i = 0; $count = 0; $len = strlen($str); while ($i < $len) { $chr = ord($str[$i]); $count++; $i++; if ($i >= $len) { break; } if ($chr & 0x80) { $chr <<= 1; while ($chr & 0x80) { $i++; $chr <<= 1; } } } } else { $count = strlen($str); } } } return $count; }
/** * Defined by Zend_Validate_Interface * * Returns true if and only if the string length of $value is at least the min option and * no greater than the max option (when the max option is not null). * * @param string $value * @return boolean */ public function isValid($value) { if (!is_string($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if ($this->_encoding !== null) { $length = iconv_strlen($value, $this->_encoding); } else { $length = iconv_strlen($value, 'UTF-8'); } $counter = array_count_values(App_Util_String::strToArray($value)); foreach (static::$doubleCountChars as $char) { if (isset($counter[$char])) { $length += $counter[$char]; } } if ($length < $this->_min) { $this->_error(self::TOO_SHORT); } if (null !== $this->_max && $this->_max < $length) { $this->_error(self::TOO_LONG); } if (count($this->_messages)) { return false; } else { return true; } }
/** * Reset forgotten password * * Used to handle data received from reset forgotten password form * * @return void */ public function execute() { $resetPasswordToken = (string) $this->getRequest()->getQuery('token'); $customerId = (int) $this->getRequest()->getQuery('id'); $password = (string) $this->getRequest()->getPost('password'); $passwordConfirmation = (string) $this->getRequest()->getPost('confirmation'); if ($password !== $passwordConfirmation) { $this->messageManager->addError(__("New Password and Confirm New Password values didn't match.")); return; } if (iconv_strlen($password) <= 0) { $this->messageManager->addError(__('New password field cannot be empty.')); $this->_redirect('*/*/createPassword', array('id' => $customerId, 'token' => $resetPasswordToken)); return; } try { $this->_customerAccountService->resetPassword($customerId, $resetPasswordToken, $password); $this->messageManager->addSuccess(__('Your password has been updated.')); $this->_redirect('*/*/login'); return; } catch (\Exception $exception) { $this->messageManager->addError(__('There was an error saving the new password.')); $this->_redirect('*/*/createPassword', array('id' => $customerId, 'token' => $resetPasswordToken)); return; } }
/** * Truncates the $string passed in, from the $start to the $length, and optionally * appends a $prefix and/or $postfix, to the string to indicate it is truncated. * * @param string $string * The string to truncate. * * @param int $start * The starting index. 0 by default. * * @param int $length * The length after which the string should be truncated. Default 50. * * @param string $prefix * The prefix to be prepended to the $string. Default is '...'. * * @param string $postfix * The postfix to be appended to the $string. Default is '...'. * * @return string * The truncated string. */ public function truncate($string, $start = 0, $length = 50, $prefix = '...', $postfix = '...') { $truncated = trim($string); $start = (int) $start; $length = (int) $length; // Return original string if max length is 0 if ($length < 1) { return $truncated; } $full_length = iconv_strlen($truncated); // Truncate if necessary if ($full_length > $length) { // Right-clipped if ($length + $start > $full_length) { $start = $full_length - $length; $postfix = ''; } // Left-clipped if ($start == 0) { $prefix = ''; } // Do truncate! $truncated = $prefix . trim(substr($truncated, $start, $length)) . $postfix; } return $truncated; }
/** * Plugin from smarty project and adapted for jtpl * @package jelix * @subpackage jtpl_plugin * @copyright 2001-2003 ispi of Lincoln, Inc. * @link http://smarty.php.net/ * @link http://jelix.org/ * @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html */ function jtpl_modifier_common_regex_replace($string, $search, $replace) { if (preg_match('!\\W(\\w+)$!s', $search, $match) && strpos($match[1], 'e') !== false) { $search = substr($search, 0, -iconv_strlen($match[1], jTpl::getEncoding())) . str_replace('e', '', $match[1]); } return preg_replace($search, $replace, $string); }
/** * Search users * * $options may include any of the following: * - page: the page of results to retrieve * - count: the number of users to retrieve per page; max is 20 * - include_entities: if set to boolean true, include embedded entities * * @param string $query * @param array $options * @throws Http\Client\Exception\ExceptionInterface if HTTP request fails or times out * @throws Exception\DomainException if unable to decode JSON payload * @return Response */ public function usersLookup($query, array $options = array()) { $this->init(); $path = 'users/lookup'; if (is_Array($query)) { $query = implode(',', $query); } $len = iconv_strlen($query, 'UTF-8'); if (0 == $len) { throw new \ZendService\Twitter\Exception\InvalidArgumentException('Query must contain at least one character'); } $params = array('screen_name' => $query); foreach ($options as $key => $value) { switch (strtolower($key)) { case 'count': $value = (int) $value; if (1 > $value || 20 < $value) { throw new Exception\InvalidArgumentException('count must be between 1 and 20'); } $params['count'] = $value; break; case 'page': $params['page'] = (int) $value; break; case 'include_entities': $params['include_entities'] = (bool) $value; break; default: break; } } $response = $this->get($path, $params); return new \ZendService\Twitter\Response($response); }
/** * 计算UTF8长度 * * @param string $string * @return number */ static function utf8_strlen($string = null) { if (empty($string)) { return 0; } return iconv_strlen($string, "UTF-8"); }
/** * Cuts log according to the limit provided * * @param string Log to cut * @param integer Limit in Kb * @see run() * @return string */ public static function cutLog($log, $limit) { $len = 0; if (function_exists('mb_strlen')) { $len += mb_strlen($log, 'UTF-8'); } elseif (function_exists('iconv_strlen')) { $len += iconv_strlen($log, 'UTF-8'); } else { // bad variant $len += strlen($log) / 2; } $max = $limit * 1024; // in kb if ($len > $max) { $cutSize = $max / 2; $func = ''; if (function_exists('iconv_substr')) { $func = 'iconv_substr'; } elseif (function_exists('mb_substr')) { $func = 'mb_substr'; } if ($func) { $head = call_user_func($func, $log, 0, $cutSize, 'UTF-8'); $tail = call_user_func($func, $log, -1 * $cutSize, $cutSize, 'UTF-8'); } else { // bad variant $head = substr($log, 0, $cutSize / 2); $tail = substr($log, -1 * $cutSize / 2); } return $head . "\n\n... content skipped (" . ($len - $max) . " bytes) ...\n\n" . $tail; } return $log; }
function adjDBValue($value, $len = -1) { if ($value === null) { return null; } if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = adjDBValue($val, $len); } } else { $value = trim($value); // NON-Multibyte here! if (strlen($value) == 0) { // NON-Multibyte here! return null; } if ($len >= 0) { // Multibyte here! if (defined('R3_APP_CHARSET_DB')) { // PHP-BUG (iconv_substr($value, 0, 1, "UFT-8"); faild!) if (iconv_strlen($value, R3_APP_CHARSET_DB) > 1) { $value = iconv_substr($value, 0, $len, R3_APP_CHARSET_DB); } } else { $value = substr($value, 0, $len); } } } return $value; }
/** * check values in the properties of the record, according on the dao definition * @return array|false list of errors or false if ok */ public function check() { $errors = array(); foreach ($this->getProperties() as $prop => $infos) { $value = $this->{$prop}; // test required if ($infos['required'] && $value === null) { $errors[$prop][] = self::ERROR_REQUIRED; continue; } switch ($infos['datatype']) { case 'varchar': case 'string': if (!is_string($value) && $value !== null) { $errors[$prop][] = self::ERROR_BAD_TYPE; break; } // test regexp if ($infos['regExp'] !== null && preg_match($infos['regExp'], $value) === 0) { $errors[$prop][] = self::ERROR_BAD_FORMAT; break; } // test maxlength et minlength $len = iconv_strlen($value, $GLOBALS['gJConfig']->charset); if ($infos['maxlength'] !== null && $len > intval($infos['maxlength'])) { $errors[$prop][] = self::ERROR_MAXLENGTH; } if ($infos['minlength'] !== null && $len < intval($infos['minlength'])) { $errors[$prop][] = self::ERROR_MINLENGTH; } break; case 'int': case 'integer': case 'numeric': case 'double': case 'float': if ($value !== null && !is_numeric($value)) { $errors[$prop][] = self::ERROR_BAD_TYPE; } break; case 'datetime': if (!preg_match('/^(\\d{4}-(((0[1,3-9]|1[0-2])-([012][0-9]|3[01]))|((02-([01][0-9]|2[0-9])))) (([01][0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9])?$/', $value)) { $errors[$prop][] = self::ERROR_BAD_FORMAT; } break; case 'time': if (!preg_match('/^((([01][0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9])?$/', $value)) { $errors[$prop][] = self::ERROR_BAD_FORMAT; } break; case 'varchardate': case 'date': if (!preg_match('/^(\\d{4}-(((0[1,3-9]|1[0-2])-([012][0-9]|3[01]))|((02-([01][0-9]|2[0-9])))))?$/', $value)) { $errors[$prop][] = self::ERROR_BAD_FORMAT; } break; } } return count($errors) ? $errors : false; }
public function __construct($value, $class = '') { $this->class = $class; $this->value = $value; switch (gettype($value)) { case 'object': $this->type = self::TYPE_OBJECT; $this->class = get_class($value); $this->cut = -1; break; case 'array': $this->type = self::TYPE_ARRAY; $this->class = self::ARRAY_ASSOC; $this->cut = $this->value = count($value); break; case 'resource': case 'unknown type': $this->type = self::TYPE_RESOURCE; $this->class = @get_resource_type($value); $this->cut = -1; break; case 'string': if ('' === $class) { $this->type = self::TYPE_STRING; $this->class = preg_match('//u', $value) ? self::STRING_UTF8 : self::STRING_BINARY; $this->cut = self::STRING_BINARY === $this->class ? strlen($value) : (function_exists('iconv_strlen') ? iconv_strlen($value, 'UTF-8') : -1); $this->value = ''; } break; } }
/** * Reset forgotten password * * Used to handle data received from reset forgotten password form * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resetPasswordToken = (string) $this->getRequest()->getQuery('token'); $customerId = (int) $this->getRequest()->getQuery('id'); $password = (string) $this->getRequest()->getPost('password'); $passwordConfirmation = (string) $this->getRequest()->getPost('password_confirmation'); if ($password !== $passwordConfirmation) { $this->messageManager->addError(__("New Password and Confirm New Password values didn't match.")); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } if (iconv_strlen($password) <= 0) { $this->messageManager->addError(__('New password field cannot be empty.')); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } try { $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $this->accountManagement->resetPassword($customerEmail, $resetPasswordToken, $password); $this->messageManager->addSuccess(__('Your password has been updated.')); $resultRedirect->setPath('*/*/login'); return $resultRedirect; } catch (\Exception $exception) { $this->messageManager->addError(__('There was an error saving the new password.')); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof Length) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Length'); } if (null === $value || '' === $value) { return; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $stringValue = (string) $value; $invalidCharset = false; if ('UTF8' === ($charset = strtoupper($constraint->charset))) { $charset = 'UTF-8'; } if ('UTF-8' === $charset) { if (!preg_match('//u', $stringValue)) { $invalidCharset = true; } elseif (function_exists('utf8_decode')) { $length = strlen(utf8_decode($stringValue)); } else { preg_replace('/./u', '', $stringValue, -1, $length); } } elseif (function_exists('mb_strlen')) { if (@mb_check_encoding($stringValue, $constraint->charset)) { $length = mb_strlen($stringValue, $constraint->charset); } else { $invalidCharset = true; } } elseif (function_exists('iconv_strlen')) { $length = @iconv_strlen($stringValue, $constraint->charset); $invalidCharset = false === $length; } else { $length = strlen($stringValue); } if ($invalidCharset) { if ($this->context instanceof ExecutionContextInterface) { $this->context->buildViolation($constraint->charsetMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ charset }}', $constraint->charset)->setInvalidValue($value)->addViolation(); } else { $this->buildViolation($constraint->charsetMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ charset }}', $constraint->charset)->setInvalidValue($value)->addViolation(); } return; } if (null !== $constraint->max && $length > $constraint->max) { if ($this->context instanceof ExecutionContextInterface) { $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->max)->setInvalidValue($value)->setPlural((int) $constraint->max)->setCode(Length::TOO_LONG_ERROR)->addViolation(); } else { $this->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->max)->setInvalidValue($value)->setPlural((int) $constraint->max)->setCode(Length::TOO_LONG_ERROR)->addViolation(); } return; } if (null !== $constraint->min && $length < $constraint->min) { if ($this->context instanceof ExecutionContextInterface) { $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->min)->setInvalidValue($value)->setPlural((int) $constraint->min)->setCode(Length::TOO_SHORT_ERROR)->addViolation(); } else { $this->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->min)->setInvalidValue($value)->setPlural((int) $constraint->min)->setCode(Length::TOO_SHORT_ERROR)->addViolation(); } } }
/** * Modifier plugin : count the number of characters in a text. * * <pre>{$mytext|count_characters} * {$mytext|count_characters:true}</pre> * * @param \Jelix\Castor\CastorCore $tpl The template * @param string $string * @param bool $include_spaces include whitespace in the character count * * @return int */ function jtpl_modifier2_common_count_characters(\Jelix\Castor\CastorCore $tpl, $string, $include_spaces = false) { if ($include_spaces) { return iconv_strlen($string, $tpl->getEncoding()); } return preg_match_all("/[^\\s]/", $string, $match); }
public function nextToken() { if ($this->_input === null) { return null; } do { if (!preg_match('/[\\p{L}]+/u', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_bytePosition)) { // It covers both cases a) there are no matches (preg_match(...) === 0) // b) error occured (preg_match(...) === FALSE) return null; } // matched string $matchedWord = $match[0][0]; // binary position of the matched word in the input stream $binStartPos = $match[0][1]; // character position of the matched word in the input stream $startPos = $this->_position + iconv_strlen(substr($this->_input, $this->_bytePosition, $binStartPos - $this->_bytePosition), 'UTF-8'); // character postion of the end of matched word in the input stream $endPos = $startPos + iconv_strlen($matchedWord, 'UTF-8'); $this->_bytePosition = $binStartPos + strlen($matchedWord); $this->_position = $endPos; $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($matchedWord, $startPos, $endPos)); } while ($token === null); // try again if token is skipped return $token; }
/** * Filter: shortens value to control's max length. * @return string */ public function checkMaxLength($value) { if ($this->control->maxlength && iconv_strlen($value, 'UTF-8') > $this->control->maxlength) { $value = iconv_substr($value, 0, $this->control->maxlength, 'UTF-8'); } return $value; }
/** * Normalize Token or remove it (if null is returned) * * @param Zend_Search_Lucene_Analysis_Token $srcToken * @return Zend_Search_Lucene_Analysis_Token */ public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { if (iconv_strlen($srcToken->getTermText(), 'UTF-8') < $this->length) { return null; } else { return $srcToken; } }
/** * Sends message to the Twitter. * @param string message encoded in UTF-8 * @return mixed ID on success or FALSE on failure * @throws TwitterException */ public function send($message) { if (iconv_strlen($message, 'UTF-8') > 140) { $message = preg_replace_callback('#https?://\\S+[^:);,.!?\\s]#', array($this, 'shortenUrl'), $message); } $res = $this->request('statuses/update', array('status' => $message)); return $res->id ? (string) $res->id : FALSE; }
/** * Split word into hypens * * Takes a word as a string and should return an array containing arrays of * two words, which each represent a possible split of a word. The german * word "Zuckerstück" for example changes its hyphens depending on the * splitting point, so the return value would look like: * * <code> * array( * array( 'Zuk-', 'kerstück' ), * array( 'Zucker-', 'stück' ), * ) * </code> * * You should always also include the concatenation character in the split * words, since it might change depending on the used language. * * @param mixed $word * @return void */ public function splitWord($word) { $splits = array(); for ($i = 1; $i < iconv_strlen($word, 'UTF-8'); ++$i) { $splits[] = array(iconv_substr($word, 0, $i) . '-', iconv_substr($word, $i)); } return $splits; }