本文整理汇总了PHP中String::strlen方法的典型用法代码示例。如果您正苦于以下问题:PHP String::strlen方法的具体用法?PHP String::strlen怎么用?PHP String::strlen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类String
的用法示例。
在下文中一共展示了String::strlen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: generateImage
/**
* Generate and display the CAPTCHA image.
* @param $captcha object Captcha
*/
function generateImage(&$captcha)
{
$width = $this->getWidth();
$height = $this->getHeight();
$length = String::strlen($captcha->getValue());
$value = $captcha->getValue();
$image = imagecreatetruecolor($width, $height);
$fg = imagecolorallocate($image, rand(128, 255), rand(128, 255), rand(128, 255));
$bg = imagecolorallocate($image, rand(0, 64), rand(0, 64), rand(0, 64));
imagefill($image, $width / 2, $height / 2, $bg);
$xStart = rand($width / 12, $width / 3);
$xEnd = rand($width * 2 / 3, $width * 11 / 12);
for ($i = 0; $i < $length; $i++) {
imagefttext($image, rand(20, 34), rand(-15, 15), $xStart + ($xEnd - $xStart) * $i / $length + rand(-5, 5), rand(40, 60), $fg, Config::getVar('captcha', 'font_location'), String::substr($value, $i, 1));
}
// Add some noise to the image.
for ($i = 0; $i < 20; $i++) {
$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
for ($j = 0; $j < 20; $j++) {
imagesetpixel($image, rand(0, $this->getWidth()), rand(0, $this->getHeight()), $color);
}
}
header('Content-type: ' . $this->getMimeType());
imagepng($image);
imagedestroy($image);
}
示例2: filterKeywords
/**
* Split a string into a clean array of keywords
* @param $text string
* @param $allowWildcards boolean
* @return array of keywords
*/
static function filterKeywords($text, $allowWildcards = false)
{
$minLength = Config::getVar('search', 'min_word_length');
$stopwords = self::_loadStopwords();
// Join multiple lines into a single string
if (is_array($text)) {
$text = join("\n", $text);
}
$cleanText = Core::cleanVar($text);
// Remove punctuation
$cleanText = String::regexp_replace('/[!"\\#\\$%\'\\(\\)\\.\\?@\\[\\]\\^`\\{\\}~]/', '', $cleanText);
$cleanText = String::regexp_replace('/[\\+,:;&\\/<=>\\|\\\\]/', ' ', $cleanText);
$cleanText = String::regexp_replace('/[\\*]/', $allowWildcards ? '%' : ' ', $cleanText);
$cleanText = String::strtolower($cleanText);
// Split into words
$words = String::regexp_split('/\\s+/', $cleanText);
// FIXME Do not perform further filtering for some fields, e.g., author names?
// Remove stopwords
$keywords = array();
foreach ($words as $k) {
if (!isset($stopwords[$k]) && String::strlen($k) >= $minLength && !is_numeric($k)) {
$keywords[] = String::substr($k, 0, SEARCH_KEYWORD_MAX_LENGTH);
}
}
return $keywords;
}
示例3: generateFileName
/**
* Generate a filename for a library file.
* @param $type int LIBRARY_FILE_TYPE_...
* @param $originalFileName string
* @return string
*/
function generateFileName($type, $originalFileName)
{
$libraryFileDao =& DAORegistry::getDAO('LibraryFileDAO');
$suffix = $this->getFileSuffixFromType($type);
$ext = $this->getExtension($originalFileName);
$truncated = $this->truncateFileName($originalFileName, 127 - String::strlen($suffix) - 1);
$baseName = String::substr($truncated, 0, String::strpos($originalFileName, $ext) - 1);
// Try a simple syntax first
$fileName = $baseName . '-' . $suffix . '.' . $ext;
if (!$libraryFileDao->filenameExists($this->pressId, $fileName)) {
return $fileName;
}
for ($i = 1;; $i++) {
$fullSuffix = $suffix . '-' . $i;
//truncate more if necessary
$truncated = $this->truncateFileName($originalFileName, 127 - String::strlen($fullSuffix) - 1);
// get the base name and append the suffix
$baseName = String::substr($truncated, 0, String::strpos($originalFileName, $ext) - 1);
//try the following
$fileName = $baseName . '-' . $fullSuffix . '.' . $ext;
if (!$libraryFileDao->filenameExists($this->pressId, $fileName)) {
return $fileName;
}
}
}
示例4: isValid
/**
* @see FormValidator::isValid()
* Value is valid if it is empty and optional or meets the specified length requirements.
* @return boolean
*/
function isValid()
{
if ($this->isEmptyAndOptional()) {
return true;
} else {
$length = String::strlen($this->getFieldValue());
switch ($this->_comparator) {
case '==':
return $length == $this->_length;
case '!=':
return $length != $this->_length;
case '<':
return $length < $this->_length;
case '>':
return $length > $this->_length;
case '<=':
return $length <= $this->_length;
case '>=':
return $length >= $this->_length;
}
return false;
}
}
示例5: isValid
/**
* Check if field value is valid.
* Value is valid if it is empty and optional or meets the specified length requirements.
* @return boolean
*/
function isValid()
{
if ($this->isEmptyAndOptional()) {
return true;
} else {
$length = String::strlen(trim($this->form->getData($this->field)));
switch ($this->comparator) {
case '==':
return $length == $this->length;
case '!=':
return $length != $this->length;
case '<':
return $length < $this->length;
case '>':
return $length > $this->length;
case '<=':
return $length <= $this->length;
case '>=':
return $length >= $this->length;
}
return false;
}
}
示例6: truncateFileName
/**
* Truncate a filename to fit in the specified length.
*/
function truncateFileName($fileName, $length = 127)
{
if (String::strlen($fileName) <= $length) {
return $fileName;
}
$ext = $this->getExtension($fileName);
$truncated = String::substr($fileName, 0, $length - 1 - String::strlen($ext)) . '.' . $ext;
return String::substr($truncated, 0, $length);
}
示例7: formatField
/**
* 格式化字段
*
* @access private
* @param mixed $typeInfo
* @param mixed $value
* @return mixed
*/
private function formatField($typeInfo, $value)
{
preg_match("/(\\w+)(\\((\\d+)\\))?/", $typeInfo, $matches);
if (isset($matches[1])) {
$type = $matches[1];
}
if (isset($matches[3])) {
$len = $matches[3];
}
$_type = "string";
$type = strtolower($type);
switch ($type) {
case 'bit':
case 'bigbit':
case 'bool':
case 'boolean':
case 'decimal':
case 'decimal':
case 'dec':
case 'double':
case 'float':
case 'int':
case 'bigint':
case 'mediumint':
case 'smallint':
case 'tinyint':
case 'real':
if (!is_numeric($value)) {
$value = 0;
}
if ($value == '' || $value == null || empty($value)) {
$value = 0;
}
$_type = 'numeric';
break;
}
if (isset($len)) {
if (!is_array($value) && String::strlen($value) > $len) {
$value = String::msubstr($value, 0, $len, 'utf-8', '');
}
}
if (is_array($value)) {
$value = serialize($value);
}
if ($_type == 'string') {
$value = '\'' . $value . '\'';
}
return $value;
}
示例8: diff
/**
* Calculate the differences between two strings and
* produce an array with three types of entries: added
* substrings, deleted substrings and unchanged substrings.
*
* The calculation is optimized to identify the common
* largest substring.
*
* The return value is an array of the following format:
*
* array(
* array( diff-type => substring ),
* array(...)
* )
*
* whereby diff-type can be one of:
* -1 = deletion
* 0 = common substring
* 1 = addition
*
* @param $originalString string
* @param $editedString string
* @return array
*/
static function diff($originalString, $editedString)
{
// Split strings into character arrays (multi-byte compatible).
foreach (array('originalStringCharacters' => $originalString, 'editedStringCharacters' => $editedString) as $characterArrayName => $string) {
${$characterArrayName} = array();
String::regexp_match_all('/./', $string, ${$characterArrayName});
if (isset(${$characterArrayName}[0])) {
${$characterArrayName} = ${$characterArrayName}[0];
}
}
// Determine the length of the strings.
$originalStringLength = count($originalStringCharacters);
$editedStringLength = count($editedStringCharacters);
// Is there anything to compare?
if ($originalStringLength == 0 && $editedStringLength == 0) {
return array();
}
// Is the original string empty?
if ($originalStringLength == 0) {
// Return the edited string as addition.
return array(array(1 => $editedString));
}
// Is the edited string empty?
if ($editedStringLength == 0) {
// Return the original string as deletion.
return array(array(-1 => $originalString));
}
// Initialize the local indices:
// 1) Create a character index for the edited string.
$characterIndex = array();
for ($characterPosition = 0; $characterPosition < $editedStringLength; $characterPosition++) {
$characterIndex[$editedStringCharacters[$characterPosition]][] = $characterPosition;
}
// 2) Initialize the substring and the length index.
$substringIndex = $lengthIndex = array();
// Iterate over the original string to identify
// the largest common string.
for ($originalPosition = 0; $originalPosition < $originalStringLength; $originalPosition++) {
// Find all occurrences of the original character
// in the target string.
$comparedCharacter = $originalStringCharacters[$originalPosition];
// Do we have a commonality between the original string
// and the edited string?
if (isset($characterIndex[$comparedCharacter])) {
// Loop over all commonalities.
foreach ($characterIndex[$comparedCharacter] as $editedPosition) {
// Calculate the current and the preceding position
// ids for indexation.
$currentPosition = $originalPosition . '-' . $editedPosition;
$previousPosition = $originalPosition - 1 . '-' . ($editedPosition - 1);
// Does the occurrence in the target string continue
// an existing common substring or does it start
// a new one?
if (isset($substringIndex[$previousPosition])) {
// This is a continuation of an existing common
// substring...
$newSubstring = $substringIndex[$previousPosition] . $comparedCharacter;
$newSubstringLength = String::strlen($newSubstring);
// Move the substring in the substring index.
$substringIndex[$currentPosition] = $newSubstring;
unset($substringIndex[$previousPosition]);
// Move the substring in the length index.
$lengthIndex[$newSubstringLength][$currentPosition] = $newSubstring;
unset($lengthIndex[$newSubstringLength - 1][$previousPosition]);
} else {
// Start a new common substring...
// Add the substring to the substring index.
$substringIndex[$currentPosition] = $comparedCharacter;
// Add the substring to the length index.
$lengthIndex[1][$currentPosition] = $comparedCharacter;
}
}
}
}
// If we have no commonalities at all then mark the original
// string as deleted and the edited string as added and
//.........这里部分代码省略.........
示例9: array
/**
* Fills the given citation object with
* meta-data retrieved from PubMed.
* @param $pmid string
* @param $citationDescription MetadataDescription
* @return MetadataDescription
*/
function &_lookup($pmid, &$citationDescription)
{
$nullVar = null;
// Use eFetch to get XML metadata for the given PMID
$lookupParams = array('db' => 'pubmed', 'mode' => 'xml', 'tool' => 'pkp-wal', 'id' => $pmid);
if (!is_null($this->getEmail())) {
$lookupParams['email'] = $this->getEmail();
}
// Call the eFetch URL and get an XML result
if (is_null($resultDOM = $this->callWebService(PUBMED_WEBSERVICE_EFETCH, $lookupParams))) {
return $nullVar;
}
$metadata = array('pub-id[@pub-id-type="pmid"]' => $pmid, 'article-title' => $resultDOM->getElementsByTagName("ArticleTitle")->item(0)->textContent, 'source' => $resultDOM->getElementsByTagName("MedlineTA")->item(0)->textContent);
if ($resultDOM->getElementsByTagName("Volume")->length > 0) {
$metadata['volume'] = $resultDOM->getElementsByTagName("Volume")->item(0)->textContent;
}
if ($resultDOM->getElementsByTagName("Issue")->length > 0) {
$metadata['issue'] = $resultDOM->getElementsByTagName("Issue")->item(0)->textContent;
}
// get list of author full names
$nlmNameSchema = new NlmNameSchema();
foreach ($resultDOM->getElementsByTagName("Author") as $authorNode) {
if (!isset($metadata['person-group[@person-group-type="author"]'])) {
$metadata['person-group[@person-group-type="author"]'] = array();
}
// Instantiate an NLM name description
$authorDescription = new MetadataDescription($nlmNameSchema, ASSOC_TYPE_AUTHOR);
// Surname
$authorDescription->addStatement('surname', $authorNode->getElementsByTagName("LastName")->item(0)->textContent);
// Given names
$givenNamesString = '';
if ($authorNode->getElementsByTagName("FirstName")->length > 0) {
$givenNamesString = $authorNode->getElementsByTagName("FirstName")->item(0)->textContent;
} elseif ($authorNode->getElementsByTagName("ForeName")->length > 0) {
$givenNamesString = $authorNode->getElementsByTagName("ForeName")->item(0)->textContent;
}
if (!empty($givenNamesString)) {
foreach (explode(' ', $givenNamesString) as $givenName) {
$authorDescription->addStatement('given-names', String::trimPunctuation($givenName));
}
}
// Suffix
if ($authorNode->getElementsByTagName("Suffix")->length > 0) {
$authorDescription->addStatement('suffix', $authorNode->getElementsByTagName("Suffix")->item(0)->textContent);
}
// Include collective names
/*if ($resultDOM->getElementsByTagName("CollectiveName")->length > 0 && $authorNode->getElementsByTagName("CollectiveName")->item(0)->textContent != '') {
// FIXME: This corresponds to an NLM-citation <collab> tag and should be part of the Metadata implementation
}*/
$metadata['person-group[@person-group-type="author"]'][] =& $authorDescription;
unset($authorDescription);
}
// Extract pagination
if (String::regexp_match_get("/^[:p\\.\\s]*(?P<fpage>[Ee]?\\d+)(-(?P<lpage>\\d+))?/", $resultDOM->getElementsByTagName("MedlinePgn")->item(0)->textContent, $pages)) {
$fPage = (int) $pages['fpage'];
$metadata['fpage'] = $fPage;
if (!empty($pages['lpage'])) {
$lPage = (int) $pages['lpage'];
// Deal with shortcuts like '382-7'
if ($lPage < $fPage) {
$lPage = (int) (String::substr($pages['fpage'], 0, -String::strlen($pages['lpage'])) . $pages['lpage']);
}
$metadata['lpage'] = $lPage;
}
}
// Get publication date
// TODO: The publication date could be in multiple places
if ($resultDOM->getElementsByTagName("ArticleDate")->length > 0) {
$publicationDate = $resultDOM->getElementsByTagName("ArticleDate")->item(0)->getElementsByTagName("Year")->item(0)->textContent . '-' . $resultDOM->getElementsByTagName("ArticleDate")->item(0)->getElementsByTagName("Month")->item(0)->textContent . '-' . $resultDOM->getElementsByTagName("ArticleDate")->item(0)->getElementsByTagName("Day")->item(0)->textContent;
$metadata['date'] = $publicationDate;
}
// Get publication type
if ($resultDOM->getElementsByTagName("PublicationType")->length > 0) {
foreach ($resultDOM->getElementsByTagName("PublicationType") as $publicationType) {
// The vast majority of items on PubMed are articles so catch these...
if (String::strpos(String::strtolower($publicationType->textContent), 'article') !== false) {
$metadata['[@publication-type]'] = NLM_PUBLICATION_TYPE_JOURNAL;
break;
}
}
}
// Get DOI if it exists
foreach ($resultDOM->getElementsByTagName("ArticleId") as $idNode) {
if ($idNode->getAttribute('IdType') == 'doi') {
$metadata['pub-id[@pub-id-type="doi"]'] = $idNode->textContent;
}
}
// Use eLink utility to find fulltext links
$lookupParams = array('dbfrom' => 'pubmed', 'cmd' => 'llinks', 'tool' => 'pkp-wal', 'id' => $pmid);
if (!is_null($resultDOM = $this->callWebService(PUBMED_WEBSERVICE_ELINK, $lookupParams))) {
// Get a list of possible links
foreach ($resultDOM->getElementsByTagName("ObjUrl") as $linkOut) {
$attributes = '';
//.........这里部分代码省略.........
示例10: _getFacetingAutosuggestions
/**
* Retrieve auto-suggestions from the faceting service.
* @param $url string
* @param $searchRequest SolrSearchRequest
* @param $userInput string
* @param $fieldName string
* @return array The generated suggestions.
*/
function _getFacetingAutosuggestions($url, $searchRequest, $userInput, $fieldName)
{
// Remove special characters from the user input.
$searchTerms = strtr($userInput, '"()+-|&!', ' ');
// Cut off the last search term.
$searchTerms = explode(' ', $searchTerms);
$facetPrefix = array_pop($searchTerms);
if (empty($facetPrefix)) {
return array();
}
// Use the remaining search query to pre-filter
// facet results. This may be an invalid query
// but edismax will deal gracefully with syntax
// errors.
$userInput = String::substr($userInput, 0, -String::strlen($facetPrefix));
switch ($fieldName) {
case 'query':
// The 'query' filter goes agains all fields.
$articleSearch = new ArticleSearch();
$solrFields = array_values($articleSearch->getIndexFieldMap());
break;
case 'indexTerms':
// The 'index terms' filter goes against keyword index fields.
$solrFields = array('discipline', 'subject', 'type', 'coverage');
break;
default:
// All other filters can be used directly.
$solrFields = array($fieldName);
}
$solrFieldString = implode('|', $solrFields);
$searchRequest->addQueryFieldPhrase($solrFieldString, $userInput);
// Construct the main query.
$params = $this->_getSearchQueryParameters($searchRequest);
if (!isset($params['q'])) {
// Use a catch-all query in case we have no limiting
// search.
$params['q'] = '*:*';
}
if ($fieldName == 'query') {
$params['facet.field'] = 'default_spell';
} else {
$params['facet.field'] = $fieldName . '_spell';
}
$facetPrefixLc = String::strtolower($facetPrefix);
$params['facet.prefix'] = $facetPrefixLc;
// Make the request.
$response = $this->_makeRequest($url, $params);
if (!is_a($response, 'DOMXPath')) {
return array();
}
// Extract term suggestions.
$nodeList = $response->query('//lst[@name="facet_fields"]/lst/int/@name');
if ($nodeList->length == 0) {
return array();
}
$termSuggestions = array();
foreach ($nodeList as $childNode) {
$termSuggestions[] = $childNode->value;
}
// Add the term suggestion to the remaining user input.
$suggestions = array();
foreach ($termSuggestions as $termSuggestion) {
// Restore case if possible.
if (strpos($termSuggestion, $facetPrefixLc) === 0) {
$termSuggestion = $facetPrefix . String::substr($termSuggestion, String::strlen($facetPrefix));
}
$suggestions[] = $userInput . $termSuggestion;
}
return $suggestions;
}
示例11: XMLParserDOMHandler
/**
* Parse an XML file using the specified handler.
* If no handler has been specified, XMLParserDOMHandler is used by default, returning a tree structure representing the document.
* @param $file string full path to the XML file
* @return object actual return type depends on the handler
*/
function &parse($file)
{
$parser =& $this->createParser();
if (!isset($this->handler)) {
// Use default handler for parsing
$handler = new XMLParserDOMHandler();
$this->setHandler($handler);
}
xml_set_object($parser, $this->handler);
xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");
import('lib.pkp.classes.file.FileWrapper');
$wrapper =& FileWrapper::wrapper($file);
// Handle responses of various types
while (true) {
$newWrapper = $wrapper->open();
if (is_object($newWrapper)) {
// Follow a redirect
unset($wrapper);
$wrapper =& $newWrapper;
unset($newWrapper);
} elseif (!$newWrapper) {
// Could not open resource -- error
$returner = false;
return $returner;
} else {
// OK, we've found the end result
break;
}
}
if (!$wrapper) {
$result = false;
return $result;
}
while (!$wrapper->eof() && ($data = $wrapper->read()) !== false) {
// if the string contains non-UTF8 characters, convert it to UTF-8 for parsing
if (Config::getVar('i18n', 'charset_normalization') == 'On' && !String::utf8_compliant($data)) {
$utf8_last = String::substr($data, String::strlen($data) - 1);
// if the string ends in a "bad" UTF-8 character, maybe it's truncated
while (!$wrapper->eof() && String::utf8_bad_find($utf8_last) === 0) {
// read another chunk of data
$data .= $wrapper->read();
$utf8_last = String::substr($data, String::strlen($data) - 1);
}
$data = String::utf8_normalize($data);
// strip any invalid UTF-8 sequences
$data = String::utf8_bad_strip($data);
// convert named entities to numeric entities
$data = strtr($data, String::getHTMLEntities());
}
// strip any invalid ASCII control characters
$data = String::utf8_strip_ascii_ctrl($data);
if (!xml_parse($parser, $data, $wrapper->eof())) {
$this->addError(xml_error_string(xml_get_error_code($parser)));
}
}
$wrapper->close();
$result =& $this->handler->getResult();
$this->destroyParser($parser);
if (isset($handler)) {
$handler->destroy();
unset($handler);
}
return $result;
}
示例12: mb_substr_replace
function mb_substr_replace($string, $replacement, $start, $length = null)
{
if (extension_loaded('mbstring') === true) {
$string_length = String::strlen($string);
if ($start < 0) {
$start = max(0, $string_length + $start);
} else {
if ($start > $string_length) {
$start = $string_length;
}
}
if ($length < 0) {
$length = max(0, $string_length - $start + $length);
} else {
if (is_null($length) === true || $length > $string_length) {
$length = $string_length;
}
}
if ($start + $length > $string_length) {
$length = $string_length - $start;
}
return String::substr($string, 0, $start) . $replacement . String::substr($string, $start + $length, $string_length - $start - $length);
}
}
示例13: abntDateFormatWithDay
/**
* @function abntDateFormatWithDay Format date taking in consideration ABNT month abbreviations
* @param $string string
* @return string
*/
function abntDateFormatWithDay($string)
{
if (is_numeric($string)) {
// it is a numeric string, we handle it as timestamp
$timestamp = (int) $string;
} else {
$timestamp = strtotime($string);
}
$format = "%d %B %Y";
if (String::strlen(strftime("%B", $timestamp)) > 4) {
$format = "%d %b. %Y";
}
return String::strtolower(strftime($format, $timestamp));
}
示例14: __construct
<?php
class String
{
private $_string;
public function __construct($string)
{
$this->_string = $string;
}
public function __call($method, $arguments)
{
$this->_string = call_user_func($method, $this->_string);
return $this;
}
public function getValue()
{
return $this->_string;
}
}
$test = new String(' test, test2 ');
$test->trim();
var_dump($test->getValue());
$test->strlen();
var_dump($test->getValue());
示例15: smartyTruncate
/**
* Override the built-in smarty truncate modifier to support mbstring
* text properly, if possible.
*/
function smartyTruncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
// Re-implement Smarty version, with multibyte-capable calls.
if ($length == 0) {
return '';
}
if (String::strlen($string) > $length) {
$length -= min($length, String::strlen($etc));
if (!$break_words && !$middle) {
$string = String::regexp_replace('/\\s+?(\\S+)?$/', '', substr($string, 0, $length + 1));
}
if (!$middle) {
return String::substr($string, 0, $length) . $etc;
} else {
return String::substr($string, 0, $length / 2) . $etc . String::substr($string, -$length / 2);
}
} else {
return $string;
}
}