当前位置: 首页>>代码示例>>PHP>>正文


PHP textlib::strlen方法代码示例

本文整理汇总了PHP中textlib::strlen方法的典型用法代码示例。如果您正苦于以下问题:PHP textlib::strlen方法的具体用法?PHP textlib::strlen怎么用?PHP textlib::strlen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在textlib的用法示例。


在下文中一共展示了textlib::strlen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: validate

 /**
  * Validates a value using a range comparison
  *
  * @param     string    $value      Value to be checked
  * @param     mixed     $options    Int for length, array for range
  * @access    public
  * @return    boolean   true if value is valid
  */
 function validate($value, $options = null)
 {
     $length = textlib::strlen($value);
     switch ($this->name) {
         case 'minlength':
             return $length >= $options;
         case 'maxlength':
             return $length <= $options;
         default:
             return $length >= $options[0] && $length <= $options[1];
     }
 }
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:20,代码来源:Range.php

示例2: get_label_name

/**
 * @uses LABEL_MAX_NAME_LENGTH
 * @param object $label
 * @return string
 */
function get_label_name($label) {
    $name = strip_tags(format_string($label->intro,true));
    if (textlib::strlen($name) > LABEL_MAX_NAME_LENGTH) {
        $name = textlib::substr($name, 0, LABEL_MAX_NAME_LENGTH)."...";
    }

    if (empty($name)) {
        // arbitrary name
        $name = get_string('modulename','label');
    }

    return $name;
}
开发者ID:Jtgadbois,项目名称:Pedadida,代码行数:18,代码来源:lib.php

示例3: action

 protected function action($message, $level, $options = null)
 {
     $columns = $this->columns;
     if ($this->datecol) {
         $columns[$this->datecol] = time();
     }
     if ($this->levelcol) {
         $columns[$this->levelcol] = $level;
     }
     $message = clean_param($message, PARAM_NOTAGS);
     // Check if the message exceeds the 255 character limit in the database,
     // if it does, shorten it so that it can be inserted successfully.
     if (textlib::strlen($message) > 255) {
         $message = textlib::substr($message, 0, 252) . '...';
     }
     $columns[$this->messagecol] = $message;
     return $this->insert_log_record($this->logtable, $columns);
 }
开发者ID:verbazend,项目名称:AWFA,代码行数:18,代码来源:database_logger.class.php

示例4: rfc2445_fold

function rfc2445_fold($string)
{
    if (textlib::strlen($string, 'utf-8') <= RFC2445_FOLDED_LINE_LENGTH) {
        return $string;
    }
    $retval = '';
    $i = 0;
    $len_count = 0;
    //multi-byte string, get the correct length
    $section_len = textlib::strlen($string, 'utf-8');
    while ($len_count < $section_len) {
        //get the current portion of the line
        $section = textlib::substr($string, $i * RFC2445_FOLDED_LINE_LENGTH, RFC2445_FOLDED_LINE_LENGTH, 'utf-8');
        //increment the length we've processed by the length of the new portion
        $len_count += textlib::strlen($section, 'utf-8');
        /* Add the portion to the return value, terminating with CRLF.HTAB
           As per RFC 2445, CRLF.HTAB will be replaced by the processor of the 
           data */
        $retval .= $section . RFC2445_CRLF . RFC2445_WSP;
        $i++;
    }
    return $retval;
}
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:23,代码来源:iCalendar_rfc2445.php

示例5: update_categories

 /**
  * Update categories
  *
  * @param array $categories The list of categories to update
  * @return null
  * @since Moodle 2.3
  */
 public static function update_categories($categories)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/course/lib.php";
     // Validate parameters.
     $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
     $transaction = $DB->start_delegated_transaction();
     foreach ($params['categories'] as $cat) {
         if (!($category = $DB->get_record('course_categories', array('id' => $cat['id'])))) {
             throw new moodle_exception('unknowcategory');
         }
         $categorycontext = context_coursecat::instance($cat['id']);
         self::validate_context($categorycontext);
         require_capability('moodle/category:manage', $categorycontext);
         if (!empty($cat['name'])) {
             if (textlib::strlen($cat['name']) > 255) {
                 throw new moodle_exception('categorytoolong');
             }
             $category->name = $cat['name'];
         }
         if (!empty($cat['idnumber'])) {
             if (textlib::strlen($cat['idnumber']) > 100) {
                 throw new moodle_exception('idnumbertoolong');
             }
             $category->idnumber = $cat['idnumber'];
         }
         if (!empty($cat['description'])) {
             $category->description = $cat['description'];
             $category->descriptionformat = external_validate_format($cat['descriptionformat']);
         }
         if (!empty($cat['theme'])) {
             $category->theme = $cat['theme'];
         }
         if (!empty($cat['parent']) && $category->parent != $cat['parent']) {
             // First check if parent exists.
             if (!($parent_cat = $DB->get_record('course_categories', array('id' => $cat['parent'])))) {
                 throw new moodle_exception('unknowcategory');
             }
             // Then check if we have capability.
             self::validate_context(get_category_or_system_context((int) $cat['parent']));
             require_capability('moodle/category:manage', get_category_or_system_context((int) $cat['parent']));
             // Finally move the category.
             move_category($category, $parent_cat);
             $category->parent = $cat['parent'];
             // Get updated path by move_category().
             $category->path = $DB->get_field('course_categories', 'path', array('id' => $category->id));
         }
         $DB->update_record('course_categories', $category);
     }
     $transaction->allow_commit();
 }
开发者ID:JP-Git,项目名称:moodle,代码行数:58,代码来源:externallib.php

示例6: format_title

 /**
  * Strips a large title to size and adds ... if title too long
  *
  * @param string title to shorten
  * @param int max character length of title
  * @return string title s() quoted and shortened if necessary
  */
 function format_title($title, $max = 64)
 {
     if (textlib::strlen($title) <= $max) {
         return s($title);
     } else {
         return s(textlib::substr($title, 0, $max - 3) . '...');
     }
 }
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:15,代码来源:block_rss_client.php

示例7: course_format_name

/**
 * given a course object with shortname & fullname, this function will
 * truncate the the number of chars allowed and add ... if it was too long
 */
function course_format_name($course, $max = 100)
{
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    $shortname = format_string($course->shortname, true, array('context' => $context));
    $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
    $str = $shortname . ': ' . $fullname;
    if (textlib::strlen($str) <= $max) {
        return $str;
    } else {
        return textlib::substr($str, 0, $max - 3) . '...';
    }
}
开发者ID:numbas,项目名称:moodle,代码行数:16,代码来源:lib.php

示例8: add_to_log

/**
 * Add an entry to the log table.
 *
 * Add an entry to the log table.  These are "action" focussed rather
 * than web server hits, and provide a way to easily reconstruct what
 * any particular student has been doing.
 *
 * @package core
 * @category log
 * @global moodle_database $DB
 * @global stdClass $CFG
 * @global stdClass $USER
 * @uses SITEID
 * @uses DEBUG_DEVELOPER
 * @uses DEBUG_ALL
 * @param    int     $courseid  The course id
 * @param    string  $module  The module name  e.g. forum, journal, resource, course, user etc
 * @param    string  $action  'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
 * @param    string  $url     The file and parameters used to see the results of the action
 * @param    string  $info    Additional description information
 * @param    string  $cm      The course_module->id if there is one
 * @param    string  $user    If log regards $user other than $USER
 * @return void
 */
function add_to_log($courseid, $module, $action, $url = '', $info = '', $cm = 0, $user = 0)
{
    // Note that this function intentionally does not follow the normal Moodle DB access idioms.
    // This is for a good reason: it is the most frequently used DB update function,
    // so it has been optimised for speed.
    global $DB, $CFG, $USER;
    if ($cm === '' || is_null($cm)) {
        // postgres won't translate empty string to its default
        $cm = 0;
    }
    if ($user) {
        $userid = $user;
    } else {
        if (session_is_loggedinas()) {
            // Don't log
            return;
        }
        $userid = empty($USER->id) ? '0' : $USER->id;
    }
    if (isset($CFG->logguests) and !$CFG->logguests) {
        if (!$userid or isguestuser($userid)) {
            return;
        }
    }
    $REMOTE_ADDR = getremoteaddr();
    $timenow = time();
    $info = $info;
    if (!empty($url)) {
        // could break doing html_entity_decode on an empty var.
        $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
    } else {
        $url = '';
    }
    // Restrict length of log lines to the space actually available in the
    // database so that it doesn't cause a DB error. Log a warning so that
    // developers can avoid doing things which are likely to cause this on a
    // routine basis.
    if (!empty($info) && textlib::strlen($info) > 255) {
        $info = textlib::substr($info, 0, 252) . '...';
        debugging('Warning: logged very long info', DEBUG_DEVELOPER);
    }
    // If the 100 field size is changed, also need to alter print_log in course/lib.php
    if (!empty($url) && textlib::strlen($url) > 100) {
        $url = textlib::substr($url, 0, 97) . '...';
        debugging('Warning: logged very long URL', DEBUG_DEVELOPER);
    }
    if (defined('MDL_PERFDB')) {
        global $PERF;
        $PERF->logwrites++;
    }
    $log = array('time' => $timenow, 'userid' => $userid, 'course' => $courseid, 'ip' => $REMOTE_ADDR, 'module' => $module, 'cmid' => $cm, 'action' => $action, 'url' => $url, 'info' => $info);
    try {
        $DB->insert_record_raw('log', $log, false);
    } catch (dml_exception $e) {
        debugging('Error: Could not insert a new entry to the Moodle log. ' . $e->error, DEBUG_ALL);
        // MDL-11893, alert $CFG->supportemail if insert into log failed
        if ($CFG->supportemail and empty($CFG->noemailever)) {
            // email_to_user is not usable because email_to_user tries to write to the logs table,
            // and this will get caught in an infinite loop, if disk is full
            $site = get_site();
            $subject = 'Insert into log failed at your moodle site ' . $site->fullname;
            $message = "Insert into log table failed at " . date('l dS \\of F Y h:i:s A') . ".\n It is possible that your disk is full.\n\n";
            $message .= "The failed query parameters are:\n\n" . var_export($log, true);
            $lasttime = get_config('admin', 'lastloginserterrormail');
            if (empty($lasttime) || time() - $lasttime > 60 * 60 * 24) {
                // limit to 1 email per day
                //using email directly rather than messaging as they may not be able to log in to access a message
                mail($CFG->supportemail, $subject, $message);
                set_config('lastloginserterrormail', time(), 'admin');
            }
        }
    }
}
开发者ID:Jtgadbois,项目名称:Pedadida,代码行数:97,代码来源:datalib.php

示例9: get_short_filename

 /**
  * Create a shorten filename
  *
  * @param string $str filename
  * @param int $maxlength max file name length
  * @return string short filename
  */
 public function get_short_filename($str, $maxlength)
 {
     if (textlib::strlen($str) >= $maxlength) {
         return trim(textlib::substr($str, 0, $maxlength)) . '...';
     } else {
         return $str;
     }
 }
开发者ID:saurabh947,项目名称:MoodleLearning,代码行数:15,代码来源:lib.php

示例10: admin_search_settings_html

/**
 * Internal function - prints the search results
 *
 * @param string $query String to search for
 * @return string empty or XHTML
 */
function admin_search_settings_html($query)
{
    global $CFG, $OUTPUT;
    if (textlib::strlen($query) < 2) {
        return '';
    }
    $query = textlib::strtolower($query);
    $adminroot = admin_get_root();
    $findings = $adminroot->search($query);
    $return = '';
    $savebutton = false;
    foreach ($findings as $found) {
        $page = $found->page;
        $settings = $found->settings;
        if ($page->is_hidden()) {
            // hidden pages are not displayed in search results
            continue;
        }
        if ($page instanceof admin_externalpage) {
            $return .= $OUTPUT->heading(get_string('searchresults', 'admin') . ' - <a href="' . $page->url . '">' . highlight($query, $page->visiblename) . '</a>', 2, 'main');
        } else {
            if ($page instanceof admin_settingpage) {
                $return .= $OUTPUT->heading(get_string('searchresults', 'admin') . ' - <a href="' . $CFG->wwwroot . '/' . $CFG->admin . '/settings.php?section=' . $page->name . '">' . highlight($query, $page->visiblename) . '</a>', 2, 'main');
            } else {
                continue;
            }
        }
        if (!empty($settings)) {
            $return .= '<fieldset class="adminsettings">' . "\n";
            foreach ($settings as $setting) {
                if (empty($setting->nosave)) {
                    $savebutton = true;
                }
                $return .= '<div class="clearer"><!-- --></div>' . "\n";
                $fullname = $setting->get_full_name();
                if (array_key_exists($fullname, $adminroot->errors)) {
                    $data = $adminroot->errors[$fullname]->data;
                } else {
                    $data = $setting->get_setting();
                    // do not use defaults if settings not available - upgradesettings handles the defaults!
                }
                $return .= $setting->output_html($data, $query);
            }
            $return .= '</fieldset>';
        }
    }
    if ($savebutton) {
        $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="' . get_string('savechanges', 'admin') . '" /></div>';
    }
    return $return;
}
开发者ID:saurabh947,项目名称:MoodleLearning,代码行数:57,代码来源:adminlib.php

示例11: clean_question_name

 /**
  * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
  * @param string $name the raw question name.
  * @return string a safe question name.
  */
 public function clean_question_name($name)
 {
     $name = clean_param($name, PARAM_TEXT);
     // Matches what the question editing form does.
     $name = trim($name);
     $trimlength = 251;
     while (textlib::strlen($name) > 255 && $trimlength > 0) {
         $name = shorten_text($name, $trimlength);
         $trimlength -= 10;
     }
     return $name;
 }
开发者ID:vinoth4891,项目名称:clinique,代码行数:17,代码来源:format.php

示例12: save_usage

    public function save_usage($preferredbehaviour, $attempt, $qas, $quizlayout) {
        $missing = array();

        $layout = explode(',', $attempt->layout);
        $questionkeys = array_combine(array_values($layout), array_keys($layout));

        $this->set_quba_preferred_behaviour($attempt->uniqueid, $preferredbehaviour);

        $i = 0;
        foreach (explode(',', $quizlayout) as $questionid) {
            if ($questionid == 0) {
                continue;
            }
            $i++;

            if (!array_key_exists($questionid, $qas)) {
                $missing[] = $questionid;
                $layout[$questionkeys[$questionid]] = $questionid;
                continue;
            }

            $qa = $qas[$questionid];
            $qa->questionusageid = $attempt->uniqueid;
            $qa->slot = $i;
            if (textlib::strlen($qa->questionsummary) > question_bank::MAX_SUMMARY_LENGTH) {
                // It seems some people write very long quesions! MDL-30760
                $qa->questionsummary = textlib::substr($qa->questionsummary,
                        0, question_bank::MAX_SUMMARY_LENGTH - 3) . '...';
            }
            $this->insert_record('question_attempts', $qa);
            $layout[$questionkeys[$questionid]] = $qa->slot;

            foreach ($qa->steps as $step) {
                $step->questionattemptid = $qa->id;
                $this->insert_record('question_attempt_steps', $step);

                foreach ($step->data as $name => $value) {
                    $datum = new stdClass();
                    $datum->attemptstepid = $step->id;
                    $datum->name = $name;
                    $datum->value = $value;
                    $this->insert_record('question_attempt_step_data', $datum, false);
                }
            }
        }

        $this->set_quiz_attempt_layout($attempt->uniqueid, implode(',', $layout));

        if ($missing) {
            notify("Question sessions for questions " .
                    implode(', ', $missing) .
                    " were missing when upgrading question usage {$attempt->uniqueid}.");
        }
    }
开发者ID:JP-Git,项目名称:moodle,代码行数:54,代码来源:upgradelib.php

示例13: get_directory_files

 /**
  * Returns all files and optionally directories
  *
  * @param int $contextid context ID
  * @param string $component component
  * @param string $filearea file area
  * @param int $itemid item ID
  * @param int $filepath directory path
  * @param bool $recursive include all subdirectories
  * @param bool $includedirs include files and directories
  * @param string $sort A fragment of SQL to use for sorting
  * @return array of stored_files indexed by pathanmehash
  */
 public function get_directory_files($contextid, $component, $filearea, $itemid, $filepath, $recursive = false, $includedirs = true, $sort = "filepath, filename")
 {
     global $DB;
     if (!($directory = $this->get_file($contextid, $component, $filearea, $itemid, $filepath, '.'))) {
         return array();
     }
     $orderby = !empty($sort) ? " ORDER BY {$sort}" : '';
     if ($recursive) {
         $dirs = $includedirs ? "" : "AND filename <> '.'";
         $length = textlib::strlen($filepath);
         $sql = "SELECT " . self::instance_sql_fields('f', 'r') . "\n                      FROM {files} f\n                 LEFT JOIN {files_reference} r\n                           ON f.referencefileid = r.id\n                     WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid\n                           AND " . $DB->sql_substr("f.filepath", 1, $length) . " = :filepath\n                           AND f.id <> :dirid\n                           {$dirs}\n                           {$orderby}";
         $params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid, 'filepath' => $filepath, 'dirid' => $directory->get_id());
         $files = array();
         $dirs = array();
         $filerecords = $DB->get_records_sql($sql, $params);
         foreach ($filerecords as $filerecord) {
             if ($filerecord->filename == '.') {
                 $dirs[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
             } else {
                 $files[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
             }
         }
         $result = array_merge($dirs, $files);
     } else {
         $result = array();
         $params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid, 'filepath' => $filepath, 'dirid' => $directory->get_id());
         $length = textlib::strlen($filepath);
         if ($includedirs) {
             $sql = "SELECT " . self::instance_sql_fields('f', 'r') . "\n                          FROM {files} f\n                     LEFT JOIN {files_reference} r\n                               ON f.referencefileid = r.id\n                         WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea\n                               AND f.itemid = :itemid AND f.filename = '.'\n                               AND " . $DB->sql_substr("f.filepath", 1, $length) . " = :filepath\n                               AND f.id <> :dirid\n                               {$orderby}";
             $reqlevel = substr_count($filepath, '/') + 1;
             $filerecords = $DB->get_records_sql($sql, $params);
             foreach ($filerecords as $filerecord) {
                 if (substr_count($filerecord->filepath, '/') !== $reqlevel) {
                     continue;
                 }
                 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
             }
         }
         $sql = "SELECT " . self::instance_sql_fields('f', 'r') . "\n                      FROM {files} f\n                 LEFT JOIN {files_reference} r\n                           ON f.referencefileid = r.id\n                     WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid\n                           AND f.filepath = :filepath AND f.filename <> '.'\n                           {$orderby}";
         $filerecords = $DB->get_records_sql($sql, $params);
         foreach ($filerecords as $filerecord) {
             $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
         }
     }
     return $result;
 }
开发者ID:nigeli,项目名称:moodle,代码行数:59,代码来源:file_storage.php

示例14: navmenulist

/**
 * Returns a popup menu with course activity modules
 *
 * Given a course
 * This function returns a small popup menu with all the
 * course activity modules in it, as a navigation menu
 * outputs a simple list structure in XHTML
 * The data is taken from the serialised array stored in
 * the course record
 *
 * @todo Finish documenting this function
 *
 * @global object
 * @uses CONTEXT_COURSE
 * @param course $course A {@link $COURSE} object.
 * @param string $sections
 * @param string $modinfo
 * @param string $strsection
 * @param string $strjumpto
 * @param int $width
 * @param string $cmid
 * @return string The HTML block
 */
function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {

    global $CFG, $OUTPUT;

    $section = -1;
    $url = '';
    $menu = array();
    $doneheading = false;

    $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);

    $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
    foreach ($modinfo->cms as $mod) {
        if (!$mod->has_view()) {
            // Don't show modules which you can't link to!
            continue;
        }

        if ($mod->sectionnum > $course->numsections) {   /// Don't show excess hidden sections
            break;
        }

        if (!$mod->uservisible) { // do not icnlude empty sections at all
            continue;
        }

        if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
            $thissection = $sections[$mod->sectionnum];

            if ($thissection->visible or !$course->hiddensections or
                      has_capability('moodle/course:viewhiddensections', $coursecontext)) {
                $thissection->summary = strip_tags(format_string($thissection->summary,true));
                if (!$doneheading) {
                    $menu[] = '</ul></li>';
                }
                if ($course->format == 'weeks' or empty($thissection->summary)) {
                    $item = $strsection ." ". $mod->sectionnum;
                } else {
                    if (textlib::strlen($thissection->summary) < ($width-3)) {
                        $item = $thissection->summary;
                    } else {
                        $item = textlib::substr($thissection->summary, 0, $width).'...';
                    }
                }
                $menu[] = '<li class="section"><span>'.$item.'</span>';
                $menu[] = '<ul>';
                $doneheading = true;

                $section = $mod->sectionnum;
            } else {
                // no activities from this hidden section shown
                continue;
            }
        }

        $url = $mod->modname .'/view.php?id='. $mod->id;
        $mod->name = strip_tags(format_string($mod->name ,true));
        if (textlib::strlen($mod->name) > ($width+5)) {
            $mod->name = textlib::substr($mod->name, 0, $width).'...';
        }
        if (!$mod->visible) {
            $mod->name = '('.$mod->name.')';
        }
        $class = 'activity '.$mod->modname;
        $class .= ($cmid == $mod->id) ? ' selected' : '';
        $menu[] = '<li class="'.$class.'">'.
                  '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
                  '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
    }

    if ($doneheading) {
        $menu[] = '</ul></li>';
    }
    $menu[] = '</ul></li></ul>';

    return implode("\n", $menu);
}
开发者ID:numbas,项目名称:moodle,代码行数:100,代码来源:weblib.php

示例15: shorten_text

/**
 * Given some text (which may contain HTML) and an ideal length,
 * this function truncates the text neatly on a word boundary if possible
 *
 * @category string
 * @global stdClass $CFG
 * @param string $text text to be shortened
 * @param int $ideal ideal string length
 * @param boolean $exact if false, $text will not be cut mid-word
 * @param string $ending The string to append if the passed string is truncated
 * @return string $truncate shortened string
 */
function shorten_text($text, $ideal = 30, $exact = false, $ending = '...')
{
    global $CFG;
    // If the plain text is shorter than the maximum length, return the whole text.
    if (textlib::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
        return $text;
    }
    // Splits on HTML tags. Each open/close/empty tag will be the first thing
    // and only tag in its 'line'.
    preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
    $total_length = textlib::strlen($ending);
    $truncate = '';
    // This array stores information about open and close tags and their position
    // in the truncated string. Each item in the array is an object with fields
    // ->open (true if open), ->tag (tag name in lower case), and ->pos
    // (byte position in truncated text).
    $tagdetails = array();
    foreach ($lines as $line_matchings) {
        // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
        if (!empty($line_matchings[1])) {
            // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
            if (preg_match('/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is', $line_matchings[1])) {
                // Do nothing.
            } else {
                if (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $line_matchings[1], $tag_matchings)) {
                    // Record closing tag.
                    $tagdetails[] = (object) array('open' => false, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate));
                } else {
                    if (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                        // Record opening tag.
                        $tagdetails[] = (object) array('open' => true, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate));
                    }
                }
            }
            // Add html-tag to $truncate'd text.
            $truncate .= $line_matchings[1];
        }
        // Calculate the length of the plain text part of the line; handle entities as one character.
        $content_length = textlib::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
        if ($total_length + $content_length > $ideal) {
            // The number of characters which are left.
            $left = $ideal - $total_length;
            $entities_length = 0;
            // Search for html entities.
            if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                // calculate the real length of all entities in the legal range
                foreach ($entities[0] as $entity) {
                    if ($entity[1] + 1 - $entities_length <= $left) {
                        $left--;
                        $entities_length += textlib::strlen($entity[0]);
                    } else {
                        // no more characters left
                        break;
                    }
                }
            }
            $breakpos = $left + $entities_length;
            // if the words shouldn't be cut in the middle...
            if (!$exact) {
                // ...search the last occurence of a space...
                for (; $breakpos > 0; $breakpos--) {
                    if ($char = textlib::substr($line_matchings[2], $breakpos, 1)) {
                        if ($char === '.' or $char === ' ') {
                            $breakpos += 1;
                            break;
                        } else {
                            if (strlen($char) > 2) {
                                // Chinese/Japanese/Korean text
                                $breakpos += 1;
                                // can be truncated at any UTF-8
                                break;
                                // character boundary.
                            }
                        }
                    }
                }
            }
            if ($breakpos == 0) {
                // This deals with the test_shorten_text_no_spaces case.
                $breakpos = $left + $entities_length;
            } else {
                if ($breakpos > $left + $entities_length) {
                    // This deals with the previous for loop breaking on the first char.
                    $breakpos = $left + $entities_length;
                }
            }
            $truncate .= textlib::substr($line_matchings[2], 0, $breakpos);
            // maximum length is reached, so get off the loop
//.........这里部分代码省略.........
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:101,代码来源:moodlelib.php


注:本文中的textlib::strlen方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。