本文整理汇总了PHP中grapheme_strlen函数的典型用法代码示例。如果您正苦于以下问题:PHP grapheme_strlen函数的具体用法?PHP grapheme_strlen怎么用?PHP grapheme_strlen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了grapheme_strlen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: validate
/**
* Checks if the passed value is valid.
*
* @param mixed $value The value that should be validated
* @param Constraint $constraint The constraint for the validation
*
* @api
*/
public function validate($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string) $value;
if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
$length = grapheme_strlen($value);
} elseif (function_exists('mb_strlen')) {
$length = mb_strlen($value, $constraint->charset);
} else {
$length = strlen($value);
}
if ($constraint->min == $constraint->max && $length != $constraint->max) {
$this->context->addViolation($constraint->exactMessage, array('{{ value }}' => $value, '{{ limit }}' => $constraint->max), null, (int) $constraint->max);
return;
}
if ($length > $constraint->max) {
$this->context->addViolation($constraint->maxMessage, array('{{ value }}' => $value, '{{ limit }}' => $constraint->max), null, (int) $constraint->max);
return;
}
if ($length < $constraint->min) {
$this->context->addViolation($constraint->minMessage, array('{{ value }}' => $value, '{{ limit }}' => $constraint->min), null, (int) $constraint->min);
}
}
示例2: testGrapheme_strlen
/**
* @covers Patchwork\PHP\Override\Intl::grapheme_strlen
*/
function testGrapheme_strlen()
{
$this->assertSame(3, grapheme_strlen('한국어'));
$this->assertSame(3, grapheme_strlen(n::normalize('한국어', n::NFD)));
$this->assertSame(3, p::grapheme_strlen('한국어'));
$this->assertSame(3, p::grapheme_strlen(n::normalize('한국어', n::NFD)));
}
示例3: validate
/**
* {@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 (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
$length = grapheme_strlen($stringValue);
} elseif (function_exists('mb_strlen')) {
$length = mb_strlen($stringValue, $constraint->charset);
} else {
$length = strlen($stringValue);
}
if (null !== $constraint->max && $length > $constraint->max) {
$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) {
$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();
}
}
示例4: excerpt
public function excerpt($field, $length = 200)
{
$text = strip_tags($this->{$field});
if (grapheme_strlen($text) > $length) {
return grapheme_substr($text, 0, $length) . '...';
} else {
return $text;
}
}
示例5: utf8Strlen
public static function utf8Strlen($string)
{
if (function_exists('grapheme_strlen')) {
return grapheme_strlen($string);
} elseif (function_exists('mb_strlen')) {
return mb_strlen($string, 'UTF-8');
} else {
return strlen($string);
}
}
示例6: validateString
private function validateString($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string, scalar or object with __toString()');
}
$value = (string) $value;
if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
$length = grapheme_strlen($value);
} elseif (function_exists('mb_strlen')) {
$length = mb_strlen($value, $constraint->charset);
} else {
$length = strlen($value);
}
$this->validateSize($constraint, $length, Size::TYPE_STRING, array('{{ value }}' => $value));
}
示例7: isValid
/**
* Checks if the passed value is valid.
*
* @param mixed $value The value that should be validated
* @param Constraint $constraint The constraint for the validation
*
* @return Boolean Whether or not the value is valid
*
* @api
*/
public function isValid($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string) $value;
if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
$length = grapheme_strlen($value);
} elseif (function_exists('mb_strlen')) {
$length = mb_strlen($value, $constraint->charset);
} else {
$length = strlen($value);
}
if ($length < $constraint->limit) {
$this->context->addViolation($constraint->message, array('{{ value }}' => $value, '{{ limit }}' => $constraint->limit));
return false;
}
return true;
}
示例8: summarize
public static function summarize($aText, $aLength, $aSuffix = '...')
{
$text = $aText;
if (grapheme_strlen($aText) > 0) {
if (grapheme_strlen($text) > $aLength) {
$text = trim($text);
$text = grapheme_substr($text, 0, $aLength);
if ($aLength > 0) {
//trim the end at a word boundary
$text = strrev($text);
if (preg_match('/(?:\\s(\\S))|\\./', $text, $matches, PREG_OFFSET_CAPTURE) && count($matches) > 1) {
$newEnd = $matches[1][1];
if ($matches[1][0] == '.') {
$newEnd++;
}
$text = grapheme_substr($text, $newEnd);
}
$text = strrev($text) . $aSuffix;
}
}
}
return $text;
}
示例9: getLength
/**
* @param string $string
*
* @return int
*/
private function getLength($string)
{
return grapheme_strlen($string);
}
示例10: filter
/**
* Returns the result of filtering $value
*
* @param mixed $value
* @return mixed
*/
public function filter($value)
{
// Store original value
$unfilteredValue = $value;
if (is_string($value)) {
// Initialization
$formatter = $this->getFormatter();
// Disable scientific notation
$formatter->setSymbol(\NumberFormatter::EXPONENTIAL_SYMBOL, null);
if ($this->getBreakingSpaceAllowed()) {
// Replace spaces with NBSP (non breaking spaces)
$value = str_replace(" ", " ", $value);
// FIXME? can be removed
}
// Parse as currency
ErrorHandler::start();
$position = 0;
$currencyCode = $this->setupCurrencyCode();
if ($this->getCurrencyCorrectness()) {
// The following parsing mode allows the predefined currency code ONLY.
// Also it should be more strict and faster than parseCurrency.
$result = $formatter->parse($value, \NumberFormatter::TYPE_DOUBLE, $position);
} else {
// The following parsing mode can work with multiple currencies.
$result = $formatter->parseCurrency($value, $resultCurrencyCode, $position);
}
$fractionDigits = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS);
// Input is a valid currency and the result is within the codomain?
if ($result !== false && (is_float($result) && !is_infinite($result) && !is_nan($result))) {
ErrorHandler::stop();
// Exit if the parsing has finished before the end of the input
if ($position < grapheme_strlen($value)) {
return $unfilteredValue;
}
// Retrieve currency symbol for the given locale and currency code
$currencySymbol = $this->getFirstCurrencySymbol($this->getLocale(), $currencyCode);
// Exit if the currency correctness is mandatory and the currency symbol is not present in the input
if ($this->getCurrencyCorrectness() && grapheme_strpos($value, $currencySymbol) === false) {
return $unfilteredValue;
}
if ($this->getScaleCorrectness()) {
$countedDecimals = $this->countDecimalDigits($value, $formatter->getSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL), $currencySymbol);
// Exit if the number of decimal digits (i.e., the scale) does not match the requirement
if ($fractionDigits !== $countedDecimals) {
return $unfilteredValue;
}
}
// Here we have a perfectly parsed (pattern correct, currency correct, scale correct) currency amount
return $result;
}
// At this stage result is FALSE and input probably is a not canonical currency amount
// Check if the currency symbol is mandatory (assiming 'parse MODE')
if ($this->getCurrencyCorrectness()) {
ErrorHandler::stop();
return $unfilteredValue;
}
// Retrieve symbols
$symbolKeys = [self::CURRENCY_SYMBOL, self::GROUP_SEPARATOR_SYMBOL, self::SEPARATOR_SYMBOL, self::INFINITY_SYMBOL, self::NAN_SYMBOL, self::POSITIVE_PREFIX, self::POSITIVE_SUFFIX, self::NEGATIVE_PREFIX, self::NEGATIVE_SUFFIX, self::FRACTION_DIGITS];
$symbols = [];
foreach ($symbolKeys as $symbol) {
$symbols[$symbol] = $this->getSymbol($symbol);
}
// Regex components
$regexSymbols = array_filter(array_unique(array_values($symbols)));
$numbers = $this->getRegexComponent(self::REGEX_NUMBERS);
$flags = $this->getRegexComponent(self::REGEX_FLAGS);
// Build allowed chars regex
$allowedChars = sprintf('#^[%s]+$#%s', $numbers . implode('', array_map('preg_quote', $regexSymbols)), $flags);
// FIXME: pay attention to NaN and INF symbols here
// Check that value contains only allowed characters (digits, group and decimal separator)
$result = false;
if (preg_match($allowedChars, $value)) {
$decimal = \NumberFormatter::create($this->getLocale(), \NumberFormatter::DECIMAL);
// Get decimal place info
// FIXME: parse and parseCurrancy could use different symbols
// when used with non default currency code
$currencySymbol = $this->getFirstCurrencySymbol($this->getLocale(), $currencyCode);
$numDecimals = $this->countDecimalDigits($value, $symbols[self::SEPARATOR_SYMBOL], $currencySymbol);
// Check if the number of decimal digits match the requirement
if ($this->getScaleCorrectness() && $numDecimals !== $fractionDigits) {
return $unfilteredValue;
}
// Ignore spaces
$value = str_replace(" ", '', $value);
// Substitute negative currency representation with negative number representation
$decimalNegPrefix = $decimal->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX);
$decimalNegSuffix = $decimal->getTextAttribute(\NumberFormatter::NEGATIVE_SUFFIX);
$currencyNegPrefix = $symbols[self::NEGATIVE_PREFIX];
$currencyNegSuffix = $symbols[self::NEGATIVE_SUFFIX];
if ($decimalNegPrefix !== $currencyNegPrefix && $decimalNegSuffix !== $currencyNegSuffix) {
$regex = sprintf('#^%s([%s%s%s]+)%s$#%s', preg_quote($currencyNegPrefix), $numbers, preg_quote($symbols[self::SEPARATOR_SYMBOL]), preg_quote($symbols[self::GROUP_SEPARATOR_SYMBOL]), preg_quote($currencyNegSuffix), $flags);
$value = preg_replace($regex, $decimalNegPrefix . '\\1' . $decimalNegSuffix, $value);
}
// Try to parse as a simple decimal (formatted) number
//.........这里部分代码省略.........
示例11: strlen
/**
* Here used as a multibyte enabled equivalent of `strlen()`.
*
* @link http://php.net/manual/en/function.grapheme-strlen.php
* @param string $string
* @return integer|void
*/
public function strlen($string)
{
return grapheme_strlen($string);
}
示例12: length
/**
* Tells how many characters there are in a string.
*
* @param string $string The string to be looked into.
*
* @return int The string's length.
*/
public static function length($string)
{
assert('is_cstring($string)', vs(isset($this), get_defined_vars()));
$res = grapheme_strlen($string);
if (is_int($res)) {
return $res;
} else {
assert('false', vs(isset($this), get_defined_vars()));
return 0;
}
}
示例13: valuesProvider
/**
* Generate dataset.
*
* Formats:
* - (positive and negative) currency amounts with their own currency symbol
* - (positive and negative) currency amounts with ISO currency symbol
* - (positive and negative) numbers (without currency symbol)
* - (positive and negative) numbers expressed in scientific notation (without currency symbol)
*
* @return array
*/
public function valuesProvider()
{
$data = [];
$values = [0, 0.1, 0.01, 1000, 1234.61, 12345678.9];
$values = array_unique(array_merge($values, array_map(function ($i) {
return -$i;
}, $values)));
foreach ($this->locales as $locale) {
$formatter = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
$currencySymbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
$isoSymbol = $formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE);
$groupSep = $formatter->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL);
$numDecimals = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS);
$posPre = $formatter->getTextAttribute(\NumberFormatter::POSITIVE_PREFIX);
$negPre = $formatter->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX);
$posSuf = $formatter->getTextAttribute(\NumberFormatter::POSITIVE_SUFFIX);
$negSuf = $formatter->getTextAttribute(\NumberFormatter::NEGATIVE_SUFFIX);
$exponantiatior = \NumberFormatter::create($locale, \NumberFormatter::SCIENTIFIC);
foreach ($values as $value) {
// Restore currency symbol
$formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $currencySymbol);
if (is_float($value)) {
// If value is float and current currency does not have cents, jump it
if ($numDecimals === 0) {
continue;
}
// Create a currency with less decimal places then required (w/ currency symbol)
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals - 1);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $formatter->format($value));
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
// Create a currency with less decimal places then required (w/o currency symbol)
$currency = preg_replace('#' . preg_quote($currencySymbol) . '#u', '', $currency);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $currency);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, $currency, $currency];
// Not filtered
// Create a currency with more decimal places then required (w/ currency symbol)
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals + 1);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $formatter->format($value));
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
// Create a currency with more decimal places then required (w/o currency symbol)
$currency = preg_replace('#' . preg_quote($currencySymbol) . '#u', '', $currency);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $currency);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, $currency, $currency];
// Not filtered
}
// Restore correct number of maximum decimal places
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals);
// Create completely formatted currency value (w/ currency symbol)
$currency = $formatter->formatCurrency($value, $isoSymbol);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $value, $currency];
// Filtered
// Create currency value with letters inside
$randomPos = rand(0, grapheme_strlen($currency) - 1);
$currency = grapheme_substr($currency, 0, $randomPos) . 'X' . grapheme_substr($currency, $randomPos);
// echo $currency . PHP_EOL;
$daa[] = [$locale, true, true, $currency, $currency];
// Not filtered
// Create currency value (w/ currency symbol) (w/o group separators)
//.........这里部分代码省略.........
示例14: mb_detect_encoding
<?php
$str = 'привет';
echo mb_detect_encoding($str) . PHP_EOL;
echo $str . PHP_EOL;
echo strlen($str) . PHP_EOL;
echo grapheme_strlen($str) . PHP_EOL;
echo mb_internal_encoding() . PHP_EOL;
echo mb_convert_encoding($str, 'utf-8', 'windows-1251') . PHP_EOL;
echo PHP_EOL;
示例15: foreach
<?php
foreach (array('møøse', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢', 'J̲o̲s̲é̲') as $s1) {
printf('String "%s" measured with strlen: %d mb_strlen: %s grapheme_strlen %s%s', $s1, strlen($s1), mb_strlen($s1), grapheme_strlen($s1), PHP_EOL);
}