作者:Flesh19
项目:magent
/**
* Get the string wrapper supporting UTF-8 character encoding
*
* @return StringWrapperInterface
*/
public function getUtf8StringWrapper()
{
if (!$this->utf8StringWrapper) {
$this->utf8StringWrapper = StringUtils::getWrapper('UTF-8');
}
return $this->utf8StringWrapper;
}
作者:eltondia
项目:Relogi
/**
* Defined by Zend\Filter\Filter
*
* @param string $value
* @return string
*/
public function filter($value)
{
// a unicode safe way of converting characters to \x00\x00 notation
$pregQuotedSeparator = preg_quote($this->separator, '#');
if (StringUtils::hasPcreUnicodeSupport()) {
$patterns = array('#(' . $pregQuotedSeparator . ')(\\p{L}{1})#u', '#(^\\p{Ll}{1})#u');
if (!extension_loaded('mbstring')) {
$replacements = array(function ($matches) {
return strtoupper($matches[2]);
}, function ($matches) {
return strtoupper($matches[1]);
});
} else {
$replacements = array(function ($matches) {
return mb_strtoupper($matches[2], 'UTF-8');
}, function ($matches) {
return mb_strtoupper($matches[1], 'UTF-8');
});
}
} else {
$patterns = array('#(' . $pregQuotedSeparator . ')([A-Za-z]{1})#', '#(^[A-Za-z]{1})#');
$replacements = array(function ($matches) {
return strtoupper($matches[2]);
}, function ($matches) {
return strtoupper($matches[1]);
});
}
$filtered = $value;
foreach ($patterns as $index => $pattern) {
$filtered = preg_replace_callback($pattern, $replacements[$index], $filtered);
}
return $filtered;
}
作者:pnaq5
项目:zf2dem
public function setUp()
{
if (!StringUtils::hasPcreUnicodeSupport()) {
return $this->markTestSkipped('PCRE is not compiled with Unicode support');
}
$this->reflection = new ReflectionProperty('Zend\\Stdlib\\StringUtils', 'hasPcreUnicodeSupport');
$this->reflection->setAccessible(true);
$this->reflection->setValue(false);
}
作者:hschlet
项目:braintacl
/**
* Validator callback for new group name - check length if necessary
*
* @param string $value
* @param array $context
* @param integer $min
* @param integer $max
* @return bool
* @internal
*/
public function validateLength($value, $context, $min, $max)
{
if ($context['Where'] == 'new') {
$length = \Zend\Stdlib\StringUtils::getWrapper('UTF-8')->strlen($value);
$result = ($length >= $min and $length <= $max);
} else {
$result = true;
// Field is ignored for existing groups
}
return $result;
}
作者:eltondia
项目:Relogi
/**
* Defined by Zend\Filter\Filter
*
* @param string $value
* @return string
*/
public function filter($value)
{
if (StringUtils::hasPcreUnicodeSupport()) {
$pattern = array('#(?<=(?:\\p{Lu}))(\\p{Lu}\\p{Ll})#', '#(?<=(?:\\p{Ll}|\\p{Nd}))(\\p{Lu})#');
$replacement = array($this->separator . '\\1', $this->separator . '\\1');
} else {
$pattern = array('#(?<=(?:[A-Z]))([A-Z]+)([A-Z][a-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#');
$replacement = array('\\1' . $this->separator . '\\2', $this->separator . '\\1');
}
return preg_replace($pattern, $replacement, $value);
}
作者:Andyyang198
项目:p
/**
* Get string wrapper
*
* @param string $encoding
*
* @return StringWrapperInterface
*/
public function getWrapper($encoding = '')
{
$encoding = strtoupper($encoding ?: Pi::config('charset'));
if (!isset($this->stringWrapper[$encoding])) {
try {
$stringWrapper = StringUtils::getWrapper(Pi::config('charset'));
} catch (\Exception $e) {
$stringWrapper = false;
}
$this->stringWrapper[$encoding] = $stringWrapper;
}
return $this->stringWrapper[$encoding];
}
作者:razvansividr
项目:pnlzf2-
/**
* Defined by Zend\Filter\FilterInterface
*
* Returns the string $value, removing all but digit characters
*
* @param string $value
* @return string
*/
public function filter($value)
{
if (!StringUtils::hasPcreUnicodeSupport()) {
// POSIX named classes are not supported, use alternative 0-9 match
$pattern = '/[^0-9]/';
} elseif (extension_loaded('mbstring')) {
// Filter for the value with mbstring
$pattern = '/[^[:digit:]]/';
} else {
// Filter for the value without mbstring
$pattern = '/[\\p{^N}]/';
}
return preg_replace($pattern, '', (string) $value);
}
作者:Flesh19
项目:magent
/**
* Defined by Zend\Filter\Filter
*
* @param string|array $value
* @return string|array
*/
public function filter($value)
{
if (!is_scalar($value) && !is_array($value)) {
return $value;
}
$value = parent::filter($value);
$lowerCaseFirst = 'lcfirst';
if (StringUtils::hasPcreUnicodeSupport() && extension_loaded('mbstring')) {
$lowerCaseFirst = function ($value) {
if (0 === mb_strlen($value)) {
return $value;
}
return mb_strtolower(mb_substr($value, 0, 1)) . mb_substr($value, 1);
};
}
return is_array($value) ? array_map($lowerCaseFirst, $value) : call_user_func($lowerCaseFirst, $value);
}
作者:idwsdt
项目:INIT-fram
/**
* Defined by Zend\Filter\FilterInterface
*
* Returns the string $value, removing all but digit characters
*
* If the value provided is non-scalar, the value will remain unfiltered
* and an E_USER_WARNING will be raised indicating it's unfilterable.
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (null === $value) {
return null;
}
if (!is_scalar($value)) {
trigger_error(sprintf('%s expects parameter to be scalar, "%s" given; cannot filter', __METHOD__, is_object($value) ? get_class($value) : gettype($value)), E_USER_WARNING);
return $value;
}
if (!StringUtils::hasPcreUnicodeSupport()) {
// POSIX named classes are not supported, use alternative 0-9 match
$pattern = '/[^0-9]/';
} elseif (extension_loaded('mbstring')) {
// Filter for the value with mbstring
$pattern = '/[^[:digit:]]/';
} else {
// Filter for the value without mbstring
$pattern = '/[\\p{^N}]/';
}
return preg_replace($pattern, '', (string) $value);
}
作者:cross-solutio
项目:yawi
protected function getKeywords($string)
{
$innerPattern = StringUtils::hasPcreUnicodeSupport() ? '[^\\p{L}]' : '[^a-z0-9ßäöü ]';
$pattern = '~' . $innerPattern . '~isu';
$stripPattern = '~^' . $innerPattern . '+|' . $innerPattern . '+$~isu';
$parts = array();
$textParts = explode(' ', $string);
foreach ($textParts as $part) {
$part = strtolower(trim($part));
$part = preg_replace($stripPattern, '', $part);
if ('' == $part) {
continue;
}
$parts[] = $part;
$tmpPart = preg_replace($pattern, ' ', $part);
if ($part != $tmpPart) {
$tmpParts = explode(' ', $tmpPart);
$tmpParts = array_filter($tmpParts);
$parts = array_merge($parts, $tmpParts);
}
}
return $parts;
}
作者:Alex--Ji
项目:homerap
/**
* Defined by Interface
*
* Returns true if and only if the $value is a valid hostname with respect to the current allow option
*
* @param string $value
* @return bool
*/
public function isValid($value)
{
if (!is_string($value)) {
$this->error(self::INVALID);
return false;
}
$this->setValue($value);
// Check input against IP address schema
if ((preg_match('/^[0-9.]*$/', $value) && strpos($value, '.') !== false || preg_match('/^[0-9a-f:.]*$/i', $value) && strpos($value, ':') !== false) && $this->getIpValidator()->setTranslator($this->getTranslator())->isValid($value)) {
if (!($this->getAllow() & self::ALLOW_IP)) {
$this->error(self::IP_ADDRESS_NOT_ALLOWED);
return false;
}
return true;
}
// Local hostnames are allowed to be partial (ending '.')
if ($this->getAllow() & self::ALLOW_LOCAL) {
if (substr($value, -1) === '.') {
$value = substr($value, 0, -1);
if (substr($value, -1) === '.') {
// Empty hostnames (ending '..') are not allowed
$this->error(self::INVALID_LOCAL_NAME);
return false;
}
}
}
$domainParts = explode('.', $value);
// Prevent partial IP V4 addresses (ending '.')
if (count($domainParts) == 4 && preg_match('/^[0-9.a-e:.]*$/i', $value) && $this->getIpValidator()->setTranslator($this->getTranslator())->isValid($value)) {
$this->error(self::INVALID_LOCAL_NAME);
}
$utf8StrWrapper = StringUtils::getWrapper('UTF-8');
// Check input against DNS hostname schema
if (count($domainParts) > 1 && $utf8StrWrapper->strlen($value) >= 4 && $utf8StrWrapper->strlen($value) <= 254) {
$status = false;
do {
// First check TLD
$matches = [];
if (preg_match('/([^.]{2,63})$/u', end($domainParts), $matches) || array_key_exists(end($domainParts), $this->validIdns)) {
reset($domainParts);
// Hostname characters are: *(label dot)(label dot label); max 254 chars
// label: id-prefix [*ldh{61} id-prefix]; max 63 chars
// id-prefix: alpha / digit
// ldh: alpha / digit / dash
// Match TLD against known list
$this->tld = strtoupper($matches[1]);
if ($this->getTldCheck()) {
if (!in_array(strtolower($this->tld), $this->validTlds) && !in_array($this->tld, $this->validTlds)) {
$this->error(self::UNKNOWN_TLD);
$status = false;
break;
}
// We have already validated that the TLD is fine. We don't want it to go through the below
// checks as new UTF-8 TLDs will incorrectly fail if there is no IDN regex for it.
array_pop($domainParts);
}
/**
* Match against IDN hostnames
* Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames
*
* @see Hostname\Interface
*/
$regexChars = [0 => '/^[a-z0-9\\x2d]{1,63}$/i'];
if ($this->getIdnCheck() && isset($this->validIdns[$this->tld])) {
if (is_string($this->validIdns[$this->tld])) {
$regexChars += (include __DIR__ . '/' . $this->validIdns[$this->tld]);
} else {
$regexChars += $this->validIdns[$this->tld];
}
}
// Check each hostname part
$check = 0;
foreach ($domainParts as $domainPart) {
// Decode Punycode domain names to IDN
if (strpos($domainPart, 'xn--') === 0) {
$domainPart = $this->decodePunycode(substr($domainPart, 4));
if ($domainPart === false) {
return false;
}
}
// Check dash (-) does not start, end or appear in 3rd and 4th positions
if ($utf8StrWrapper->strpos($domainPart, '-') === 0 || $utf8StrWrapper->strlen($domainPart) > 2 && $utf8StrWrapper->strpos($domainPart, '-', 2) == 2 && $utf8StrWrapper->strpos($domainPart, '-', 3) == 3 || $utf8StrWrapper->strpos($domainPart, '-') === $utf8StrWrapper->strlen($domainPart) - 1) {
$this->error(self::INVALID_DASH);
$status = false;
break 2;
}
// Check each domain part
$checked = false;
foreach ($regexChars as $regexKey => $regexChar) {
$status = preg_match($regexChar, $domainPart);
if ($status > 0) {
$length = 63;
//.........这里部分代码省略.........
作者:kristjanAn
项目:SimpleI
public function importCsv($csv, User $user, $bankCode)
{
if ($csv['error'] != 0) {
throw new \InvalidArgumentException('System has errors with uploaded file');
}
if (!$user) {
return;
}
$counts = array(0, 0);
if (($handle = fopen($csv['tmp_name'], 'r')) !== false) {
// fgets($handle, 4096);
$data = fgets($handle, 4096);
$delimiter = ',';
if (count(explode(';', $data)) > 8) {
$delimiter = ';';
}
rewind($handle);
$data = fgetcsv($handle, 4096, $delimiter);
if (in_array($data[0], array('Konto', 'Kliendi konto'))) {
$data = fgetcsv($handle, 4096, $delimiter);
}
rewind($handle);
while (($data = fgetcsv($handle, 4096, $delimiter)) !== false) {
if (in_array($data[0], array('Konto', 'Kliendi konto'))) {
continue;
}
if ($bankCode == BankTransaction::BANK_KREDIIDIPANK) {
//valjavote.csv
$name = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[14]));
$referenceNumber = trim($data[22]);
$sum = str_replace(',', '.', trim($data[3]));
$paymentDate = \DateTime::createFromFormat('d.m.Y', $data[0]);
$description = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[21]));
$archiveSign = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[1]));
$payerIban = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[16]));
} elseif ($bankCode == BankTransaction::BANK_SEB) {
$name = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[4]));
$referenceNumber = trim($data[9]);
$sum = str_replace(',', '.', (trim($data[7] == 'D') ? -1 : 1) * trim(str_replace(',', '.', $data[8])));
$paymentDate = \DateTime::createFromFormat('d.m.Y', $data[2]);
$description = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[11]));
$archiveSign = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[10]));
$payerIban = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[3]));
} elseif ($bankCode == BankTransaction::BANK_SWED) {
//toimingud.csv
$name = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[4]));
$referenceNumber = trim($data[9]);
$sum = str_replace(',', '.', trim($data[8]));
$paymentDate = \DateTime::createFromFormat('d-m-Y', $data[2]);
$description = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[11]));
$archiveSign = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[10]));
$payerIban = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[3]));
} elseif ($bankCode == BankTransaction::BANK_NORDEA) {
$name = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[4]));
$referenceNumber = trim($data[7]);
$sum = str_replace(',', '.', (trim($data[5] == 'D') ? -1 : 1) * trim(str_replace(',', '.', $data[6])));
$paymentDate = \DateTime::createFromFormat('d.m.Y', $data[2]);
$description = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[9]));
$archiveSign = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[8]));
$payerIban = StringUtils::getWrapper('ISO-8859-1', 'UTF-8')->convert(trim($data[3]));
}
if ($name == null || $paymentDate === false) {
continue;
}
$paymentDate->setTime(0, 0, 0);
if ($archiveSign !== null && $archiveSign !== '') {
$transaction = $this->entityManager->getRepository(BankTransaction::getClass())->findOneBy(array('name' => $name, 'referenceNumber' => $referenceNumber, 'sum' => $sum, 'paymentDate' => $paymentDate, 'description' => $description, 'archiveSign' => $archiveSign));
if ($transaction != null) {
continue;
}
}
$transaction = new BankTransaction();
$transaction->setName($name);
$transaction->setReferenceNumber($referenceNumber);
$transaction->setSum($sum);
$transaction->setType($sum < 0 ? BankTransaction::TYPE_OUTGOING : BankTransaction::TYPE_INCOMING);
$transaction->setPaymentDate($paymentDate);
$transaction->setDescription($description);
$transaction->setArchiveSign($archiveSign);
$transaction->setPayerIban($payerIban);
$transaction->setPaymentType(BankTransaction::PAYMENT_TYPE_TRANSFER);
$transaction->setUser($user);
$this->saveTransaction($transaction);
if ($sum > 0) {
$counts[1]++;
$this->autoAssociateIncoming($transaction);
} else {
$counts[0]++;
}
}
fclose($handle);
}
return $counts;
}
作者:Flesh19
项目:magent
/**
* Encode a text to match console encoding
*
* @param string $text
* @return string the encoding text
*/
public function encodeText($text)
{
if ($this->isUtf8()) {
if (StringUtils::isValidUtf8($text)) {
return $text;
}
return utf8_encode($text);
}
if (StringUtils::isValidUtf8($text)) {
return utf8_decode($text);
}
return $text;
}
作者:razvansividr
项目:pnlzf2-
/**
* Pad a string to a certain length with another string
*
* @param string $input
* @param integer $padLength
* @param string $padString
* @param integer $padType
* @return string
*/
public function strPad($input, $padLength, $padString = ' ', $padType = STR_PAD_RIGHT)
{
if (StringUtils::isSingleByteEncoding($this->getEncoding())) {
return str_pad($input, $padLength, $padString, $padType);
}
$lengthOfPadding = $padLength - $this->strlen($input);
if ($lengthOfPadding <= 0) {
return $input;
}
$padStringLength = $this->strlen($padString);
if ($padStringLength === 0) {
return $input;
}
$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 = $this->substr($padString, 0, $lastStringLeftLength);
$lastStringRight = $this->substr($padString, 0, $lastStringRightLength);
return str_repeat($padString, $repeatCountLeft) . $lastStringLeft . $input . str_repeat($padString, $repeatCountRight) . $lastStringRight;
}
$lastString = $this->substr($padString, 0, $lengthOfPadding % $padStringLength);
if ($padType === STR_PAD_LEFT) {
return str_repeat($padString, $repeatCount) . $lastString . $input;
}
return $input . str_repeat($padString, $repeatCount) . $lastString;
}
作者:leodid
项目:moneylaundr
/**
* Get all the regex components
*
* @return array
*/
public function getRegexComponents()
{
if ($this->regexComponents == null) {
$this->regexComponents[self::REGEX_NUMBERS] = '0-9';
$this->regexComponents[self::REGEX_FLAGS] = '';
if (StringUtils::hasPcreUnicodeSupport()) {
$this->regexComponents[self::REGEX_NUMBERS] = '\\p{N}';
$this->regexComponents[self::REGEX_FLAGS] .= 'u';
}
}
return $this->regexComponents;
}
作者:hschlet
项目:braintacl
/**
* Validator callback
*
* @internal
* @param string $value
* @param array $context
* @param string $type Field datatype
* @return bool TRUE if $value is valid for given type
*/
public function validateField($value, $context, $type)
{
switch ($type) {
case 'text':
$result = \Zend\Stdlib\StringUtils::getWrapper('UTF-8')->strlen($value) <= 255;
break;
case 'integer':
case 'float':
case 'date':
$result = $this->validateType($value, $context, $type);
break;
default:
$result = true;
}
return $result;
}
作者:totoloui
项目:ZF2-Aut
/**
* Sets a new encoding to use
*
* @param string $encoding
* @return StringLength
* @throws Exception\InvalidArgumentException
*/
public function setEncoding($encoding)
{
$this->stringWrapper = StringUtils::getWrapper($encoding);
$this->options['encoding'] = $encoding;
return $this;
}
作者:ErR16
项目:torrentpie
/**
* Returns true if and only if $value is a floating-point value. Uses the formal definition of a float as described
* in the PHP manual: {@link http://www.php.net/float}
*
* @param string $value
* @return bool
* @throws Exception\InvalidArgumentException
*/
public function isValid($value)
{
if (!is_scalar($value) || is_bool($value)) {
$this->error(self::INVALID);
return false;
}
$this->setValue($value);
if (is_float($value) || is_int($value)) {
return true;
}
// Need to check if this is scientific formatted string. If not, switch to decimal.
$formatter = new NumberFormatter($this->getLocale(), NumberFormatter::SCIENTIFIC);
if (intl_is_failure($formatter->getErrorCode())) {
throw new Exception\InvalidArgumentException($formatter->getErrorMessage());
}
if (StringUtils::hasPcreUnicodeSupport()) {
$exponentialSymbols = '[Ee' . $formatter->getSymbol(NumberFormatter::EXPONENTIAL_SYMBOL) . ']+';
$search = '/' . $exponentialSymbols . '/u';
} else {
$exponentialSymbols = '[Ee]';
$search = '/' . $exponentialSymbols . '/';
}
if (!preg_match($search, $value)) {
$formatter = new NumberFormatter($this->getLocale(), NumberFormatter::DECIMAL);
}
/**
* @desc There are seperator "look-alikes" for decimal and group seperators that are more commonly used than the
* official unicode chracter. We need to replace those with the real thing - or remove it.
*/
$groupSeparator = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
$decSeparator = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
//NO-BREAK SPACE and ARABIC THOUSANDS SEPARATOR
if ($groupSeparator == " ") {
$value = str_replace(' ', $groupSeparator, $value);
} elseif ($groupSeparator == "٬") {
//NumberFormatter doesn't have grouping at all for Arabic-Indic
$value = str_replace(array('\'', $groupSeparator), '', $value);
}
//ARABIC DECIMAL SEPARATOR
if ($decSeparator == "٫") {
$value = str_replace(',', $decSeparator, $value);
}
$groupSeparatorPosition = $this->wrapper->strpos($value, $groupSeparator);
$decSeparatorPosition = $this->wrapper->strpos($value, $decSeparator);
//We have seperators, and they are flipped. i.e. 2.000,000 for en-US
if ($groupSeparatorPosition && $decSeparatorPosition && $groupSeparatorPosition > $decSeparatorPosition) {
return false;
}
//If we have Unicode support, we can use the real graphemes, otherwise, just the ASCII characters
$decimal = '[' . preg_quote($decSeparator, '/') . ']';
$prefix = '[+-]';
$exp = $exponentialSymbols;
$numberRange = '0-9';
$useUnicode = '';
$suffix = '';
if (StringUtils::hasPcreUnicodeSupport()) {
$prefix = '[' . preg_quote($formatter->getTextAttribute(NumberFormatter::POSITIVE_PREFIX) . $formatter->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX) . $formatter->getSymbol(NumberFormatter::PLUS_SIGN_SYMBOL) . $formatter->getSymbol(NumberFormatter::MINUS_SIGN_SYMBOL), '/') . ']{0,3}';
$suffix = $formatter->getTextAttribute(NumberFormatter::NEGATIVE_SUFFIX) ? '[' . preg_quote($formatter->getTextAttribute(NumberFormatter::POSITIVE_SUFFIX) . $formatter->getTextAttribute(NumberFormatter::NEGATIVE_SUFFIX) . $formatter->getSymbol(NumberFormatter::PLUS_SIGN_SYMBOL) . $formatter->getSymbol(NumberFormatter::MINUS_SIGN_SYMBOL), '/') . ']{0,3}' : '';
$numberRange = '\\p{N}';
$useUnicode = 'u';
}
/**
* @desc Match against the formal definition of a float. The
* exponential number check is modified for RTL non-Latin number
* systems (Arabic-Indic numbering). I'm also switching out the period
* for the decimal separator. The formal definition leaves out +- from
* the integer and decimal notations so add that. This also checks
* that a grouping sperator is not in the last GROUPING_SIZE graphemes
* of the string - i.e. 10,6 is not valid for en-US.
* @see http://www.php.net/float
*/
$lnum = '[' . $numberRange . ']+';
$dnum = '(([' . $numberRange . ']*' . $decimal . $lnum . ')|(' . $lnum . $decimal . '[' . $numberRange . ']*))';
$expDnum = '((' . $prefix . '((' . $lnum . '|' . $dnum . ')' . $exp . $prefix . $lnum . ')' . $suffix . ')|' . '(' . $suffix . '(' . $lnum . $prefix . $exp . '(' . $dnum . '|' . $lnum . '))' . $prefix . '))';
// LEFT-TO-RIGHT MARK (U+200E) is messing up everything for the handful
// of locales that have it
$lnumSearch = str_replace("", '', '/^' . $prefix . $lnum . $suffix . '$/' . $useUnicode);
$dnumSearch = str_replace("", '', '/^' . $prefix . $dnum . $suffix . '$/' . $useUnicode);
$expDnumSearch = str_replace("", '', '/^' . $expDnum . '$/' . $useUnicode);
$value = str_replace("", '', $value);
$unGroupedValue = str_replace($groupSeparator, '', $value);
// No strrpos() in wrappers yet. ICU 4.x doesn't have grouping size for
// everything. ICU 52 has 3 for ALL locales.
$groupSize = $formatter->getAttribute(NumberFormatter::GROUPING_SIZE) ? $formatter->getAttribute(NumberFormatter::GROUPING_SIZE) : 3;
$lastStringGroup = $this->wrapper->substr($value, -$groupSize);
if ((preg_match($lnumSearch, $unGroupedValue) || preg_match($dnumSearch, $unGroupedValue) || preg_match($expDnumSearch, $unGroupedValue)) && false === $this->wrapper->strpos($lastStringGroup, $groupSeparator)) {
return true;
}
return false;
}
作者:ralfegger
项目:zftoo
public function __construct(Console $console, $displayData = false)
{
$this->console = $console;
$this->stringUtils = StringUtils::getWrapper();
$this->displayData = $displayData;
}
作者:leodid
项目:moneylaundr
/**
* Returns true if and only if $value is a number correctly expressed with the scientific notation
*
* Note that it can only validate string inputs.
*
* @param mixed $value
* @return bool
*/
public function isValid($value)
{
if (!is_scalar($value) || is_bool($value)) {
$this->error(self::INVALID_INPUT);
return false;
}
$formatter = new \NumberFormatter($this->getLocale(), \NumberFormatter::SCIENTIFIC);
$flags = 'i';
$expSymbol = 'E';
if (StringUtils::hasPcreUnicodeSupport()) {
$expSymbol = preg_quote($formatter->getSymbol(\NumberFormatter::EXPONENTIAL_SYMBOL));
$flags .= 'u';
}
// Check that exponentation symbol is present
$search = str_replace("", '', sprintf('/%s/%s', $expSymbol, $flags));
$value = str_replace("", '', $value);
if (!preg_match($search, $value)) {
$this->error(self::NOT_SCIENTIFIC);
return false;
}
// Check that the number expressed in scientific notation is a valid number
$float = new IsFloat(['locale' => $this->getLocale()]);
if (!$float->isValid($value)) {
$this->error(self::NOT_NUMBER);
return false;
}
return true;
}