• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP preg_replace_callback函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中preg_replace_callback函数的典型用法代码示例。如果您正苦于以下问题:PHP preg_replace_callback函数的具体用法?PHP preg_replace_callback怎么用?PHP preg_replace_callback使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: filter_xss

function filter_xss($string)
{
    // Only operate on valid UTF-8 strings. This is necessary to prevent cross
    // site scripting issues on Internet Explorer 6.
    if (!validate_utf8($string)) {
        return '';
    }
    $allowed_tags = dPgetConfig('filter_allowed_tags', array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'table', 'tr', 'td', 'tbody', 'thead', 'br', 'b', 'i'));
    // Store the input format
    _filter_xss_split($allowed_tags, TRUE);
    // Remove NUL characters (ignored by some browsers)
    $string = str_replace(chr(0), '', $string);
    // Remove Netscape 4 JS entities
    $string = preg_replace('%&\\s*\\{[^}]*(\\}\\s*;?|$)%', '', $string);
    // Defuse all HTML entities
    $string = str_replace('&', '&', $string);
    // Change back only well-formed entities in our whitelist
    // Decimal numeric entities
    $string = preg_replace('/&#([0-9]+;)/', '&#\\1', $string);
    // Hexadecimal numeric entities
    $string = preg_replace('/&#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\\1', $string);
    // Named entities
    $string = preg_replace('/&([A-Za-z][A-Za-z0-9]*;)/', '&\\1', $string);
    return preg_replace_callback('%
    (
    <(?=[^a-zA-Z!/])  # a lone <
    |                 # or
    <!--.*?-->        # a comment
    |                 # or
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
    |                 # or
    >                 # just a >
    )%x', '_filter_xss_split', $string);
}
开发者ID:222elm,项目名称:dotprojectFrame,代码行数:34,代码来源:filter.php


示例2: multilang_filter

function multilang_filter($courseid, $text)
{
    global $CFG;
    // [pj] I don't know about you but I find this new implementation funny :P
    // [skodak] I was laughing while rewriting it ;-)
    // [nicolasconnault] Should support inverted attributes: <span class="multilang" lang="en"> (Doesn't work curently)
    // [skodak] it supports it now, though it is slower - any better idea?
    if (empty($text) or is_numeric($text)) {
        return $text;
    }
    if (empty($CFG->filter_multilang_force_old) and !empty($CFG->filter_multilang_converted)) {
        // new syntax
        $search = '/(<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>.*?<\\/span>)(\\s*<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>.*?<\\/span>)+/is';
    } else {
        // old syntax
        $search = '/(<(?:lang|span) lang="[a-zA-Z0-9_-]*".*?>.*?<\\/(?:lang|span)>)(\\s*<(?:lang|span) lang="[a-zA-Z0-9_-]*".*?>.*?<\\/(?:lang|span)>)+/is';
    }
    $result = preg_replace_callback($search, 'multilang_filter_impl', $text);
    if (is_null($result)) {
        return $text;
        //error during regex processing (too many nested spans?)
    } else {
        return $result;
    }
}
开发者ID:JackCanada,项目名称:moodle-hacks,代码行数:25,代码来源:filter.php


示例3: parseEscapeSequences

 /**
  * Parses escape sequences in strings (all string types apart from single quoted).
  *
  * @param string      $str   String without quotes
  * @param null|string $quote Quote type
  *
  * @return string String with escape sequences parsed
  */
 public static function parseEscapeSequences($str, $quote)
 {
     if (null !== $quote) {
         $str = str_replace('\\' . $quote, $quote, $str);
     }
     return preg_replace_callback('~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3})~', array(__CLASS__, 'parseCallback'), $str);
 }
开发者ID:TheTypoMaster,项目名称:SPHERE-Framework,代码行数:15,代码来源:String.php


示例4: recurse

function recurse($dir)
{
    echo "{$dir}\n";
    foreach (glob("{$dir}/*") as $filename) {
        if (is_dir($filename)) {
            recurse($filename);
        } elseif (eregi('\\.xml$', $filename)) {
            //~ echo "$filename\n";
            $file = file_get_contents($filename);
            $file = preg_replace_callback('~(<!\\[CDATA\\[)(.*)(\\]\\]>)~sU', "callback_htmlentities", $file);
            $file = preg_replace_callback('~(<!--)(.*)(-->)~sU', "callback_htmlentities", $file);
            // isn't in one function as it can match !CDATA[[...-->
            if ($GLOBALS["MODE"] == "escape") {
                $file = preg_replace_callback('~<(' . $GLOBALS['GOOD_TAGS'] . ')( [^>]*)?>(.*)</\\1>~sU', "callback_make_value", $file);
            } else {
                // "unescape"
                $file = str_replace("\r", "", $file);
                // for Windows version of Aspell
                $file = preg_replace_callback('~<(' . $GLOBALS['GOOD_TAGS'] . ')( [^>]*)? aspell="(.*)"/>~sU', "callback_make_contents", $file);
            }
            $fp = fopen($filename, "wb");
            fwrite($fp, $file);
            fclose($fp);
        }
    }
}
开发者ID:marczych,项目名称:hack-hhvm-docs,代码行数:26,代码来源:aspell.php


示例5: custom_permalinks

function custom_permalinks($title)
{
    $title = sanitize_title_with_dashes($title);
    $toupper = create_function('$m', 'return strtoupper($m[0]);');
    $title = preg_replace_callback('/(%[0-9a-f]{2}?)+/', $toupper, $title);
    return $title;
}
开发者ID:rexin,项目名称:zhibei-tib,代码行数:7,代码来源:permalink-encoding.php


示例6: axisFixer

function axisFixer($string)
{
    $string = preg_replace_callback("/\\d+[\\d\\.]*/", "axisStrings", $string);
    $string = rangeFixer($string, "1");
    $string = preg_replace_callback("/\\d+[\\d\\.]*\\s+steps/", "axisSteps", $string);
    return $string;
}
开发者ID:grlf,项目名称:eyedock,代码行数:7,代码来源:formatNumberText.php


示例7: filterIEFilters

 /**
  * Filters all IE filters (AlphaImageLoader filter) through a callable.
  *
  * @param string   $content  The CSS
  * @param callable $callback A PHP callable
  *
  * @return string The filtered CSS
  */
 public static function filterIEFilters($content, $callback)
 {
     $pattern = static::REGEX_IE_FILTERS;
     return static::filterCommentless($content, function ($part) use(&$callback, $pattern) {
         return preg_replace_callback($pattern, $callback, $part);
     });
 }
开发者ID:mohamedsharaf,项目名称:assetic,代码行数:15,代码来源:CssUtils.php


示例8: parse

 protected function parse($st)
 {
     if (preg_replace_callback('#<tr>(.{1,100}нефтебаза.+?|.{1,200}[bg]>[АП]З[СК]?.+?)</tr>#su', function ($x) {
         if (strpos($x[1], 'нефтебаза')) {
             if (strpos($x[1], 'Туапсе')) {
                 $GLOBALS['operator'] = 'ОАО "Роснефть-Туапсенефтепродукт"';
             } else {
                 if ($this->region == 'RU-KDA') {
                     $GLOBALS['operator'] = 'ОАО "Роснефть-Кубаньнефтепродукт"';
                 } else {
                     $GLOBALS['operator'] = '';
                 }
             }
         }
         if (!preg_match('#' . "(?<ref>\\d+)" . '.+?/>(?<_addr>.+?)</td' . "#su", $x[0], $obj)) {
             return;
         }
         if (isset($GLOBALS['operator'])) {
             $obj['operator'] = $GLOBALS['operator'];
         }
         $obj['_addr'] = trim(strip_tags(str_replace('&nbsp;', ' ', $obj['_addr'])));
         $obj["fuel:octane_98"] = strpos($x[0], 'Аи-98') ? 'yes' : '';
         $obj["fuel:octane_95"] = strpos($x[0], 'Аи-95') ? 'yes' : '';
         $obj["fuel:octane_92"] = strpos($x[0], 'Аи-92') ? 'yes' : '';
         $obj["fuel:octane_80"] = strpos($x[0], 'Аи-80') ? 'yes' : '';
         $obj["fuel:diesel"] = strpos($x[0], 'ДТ') ? 'yes' : '';
         $this->addObject($this->makeObject($obj));
     }, $st)) {
     }
 }
开发者ID:KooLru,项目名称:validator,代码行数:30,代码来源:rosneft.php


示例9: ParseHeaderFooter

 private function ParseHeaderFooter($str, $uid = null)
 {
     $str = preg_replace_callback('/%sort_?link:([a-z0-9_]+)%/i', array(__CLASS__, 'GenSortlink'), $str);
     if (strpos($str, '%search_form%') !== false) {
         wpfb_loadclass('Output');
         $str = str_replace('%search_form%', WPFB_Output::GetSearchForm("", $_GET), $str);
     }
     $str = preg_replace_callback('/%print_?(script|style):([a-z0-9_-]+)%/i', array(__CLASS__, 'PrintScriptCallback'), $str);
     if (empty($uid)) {
         $uid = uniqid();
     }
     $str = str_replace('%uid%', $uid, $str);
     $count = 0;
     $str = preg_replace("/jQuery\\((.+?)\\)\\.dataTable\\s*\\((.*?)\\)(\\.?.*?)\\s*;/", 'jQuery($1).dataTable((function(options){/*%WPFB_DATA_TABLE_OPTIONS_FILTER%*/})($2))$3;', $str, -1, $count);
     if ($count > 0) {
         $dataTableOptions = array();
         list($sort_field, $sort_dir) = wpfb_call('Output', 'ParseSorting', $this->current_list->file_order);
         $file_tpl = WPFB_Core::GetTpls('file', $this->file_tpl_tag);
         if (($p = strpos($file_tpl, "%{$sort_field}%")) > 0) {
             // get the column index of field to sort
             $col_index = substr_count($file_tpl, "</t", 0, $p);
             $dataTableOptions["aaSorting"] = array(array($col_index, strtolower($sort_dir)));
         }
         if ($this->current_list->page_limit > 0) {
             $dataTableOptions["iDisplayLength"] = $this->current_list->page_limit;
         }
         $str = str_replace('/*%WPFB_DATA_TABLE_OPTIONS_FILTER%*/', " var wpfbOptions = " . json_encode($dataTableOptions) . "; " . " if('object' == typeof(options)) { for (var v in options) { wpfbOptions[v] = options[v]; } }" . " return wpfbOptions; ", $str);
     }
     return $str;
 }
开发者ID:parsonsc,项目名称:dofe,代码行数:30,代码来源:ListTpl.php


示例10: getFromRouter

 public static function getFromRouter(Router $router)
 {
     $mode = $router->getMode();
     $parameters = [];
     $path = preg_replace_callback('/\\/\\${.*}/U', function ($matches) use(&$parameters) {
         $parameters[] = preg_replace('/\\/|\\$|\\{|\\}/', '', $matches[0]);
         return '';
     }, $router->getPath());
     $patharr = array_merge(explode('/', $router->getBase()), explode('/', $path));
     $path = array_filter(array_map(function ($p) {
         return \camelCase($p, true, '-');
     }, $patharr));
     if ($mode === Router::MOD_RESTFUL) {
         $request = $router->getRequest();
         $method = strtoupper($_POST['_method'] ?? $request->getMethod());
         $action = $router->getActionOfRestful($method);
         if ($action === null) {
             throw new \Leno\Http\Exception(501);
         }
     } else {
         $action = preg_replace_callback('/^[A-Z]/', function ($matches) {
             if (isset($matches[0])) {
                 return strtolower($matches[0]);
             }
         }, preg_replace('/\\..*$/', '', array_pop($path)));
     }
     try {
         return (new self(implode('\\', $path) . 'Controller'))->setMethod($action)->setParameters($parameters);
     } catch (\Exception $ex) {
         logger()->err((string) $ex);
         throw new \Leno\Http\Exception(404);
     }
 }
开发者ID:hackyoung,项目名称:leno,代码行数:33,代码来源:Target.php


示例11: execute

 /**
  * Here we do the work
  */
 public function execute($comment)
 {
     global $_CONF, $_TABLES, $_USER, $LANG_SX00;
     if (isset($_USER['uid']) && $_USER['uid'] > 1) {
         $uid = $_USER['uid'];
     } else {
         $uid = 1;
     }
     /**
      * Include Blacklist Data
      */
     $result = DB_query("SELECT value FROM {$_TABLES['spamx']} WHERE name='Personal'", 1);
     $nrows = DB_numRows($result);
     // named entities
     $comment = html_entity_decode($comment);
     // decimal notation
     $comment = preg_replace_callback('/&#(\\d+);/m', array($this, 'callbackDecimal'), $comment);
     // hex notation
     $comment = preg_replace_callback('/&#x([a-f0-9]+);/mi', array($this, 'callbackHex'), $comment);
     $ans = 0;
     for ($i = 1; $i <= $nrows; $i++) {
         list($val) = DB_fetchArray($result);
         $val = str_replace('#', '\\#', $val);
         if (preg_match("#{$val}#i", $comment)) {
             $ans = 1;
             // quit on first positive match
             SPAMX_log($LANG_SX00['foundspam'] . $val . $LANG_SX00['foundspam2'] . $uid . $LANG_SX00['foundspam3'] . $_SERVER['REMOTE_ADDR']);
             break;
         }
     }
     return $ans;
 }
开发者ID:spacequad,项目名称:glfusion,代码行数:35,代码来源:BlackList.Examine.class.php


示例12: formatMessage

 public static function formatMessage(Rule $rule, $withValue = TRUE)
 {
     $message = $rule->message;
     if ($message instanceof Nette\Utils\Html) {
         return $message;
     } elseif ($message === NULL && is_string($rule->validator) && isset(static::$messages[$rule->validator])) {
         $message = static::$messages[$rule->validator];
     } elseif ($message == NULL) {
         // intentionally ==
         trigger_error("Missing validation message for control '{$rule->control->getName()}'.", E_USER_WARNING);
     }
     if ($translator = $rule->control->getForm()->getTranslator()) {
         $message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : NULL);
     }
     $message = preg_replace_callback('#%(name|label|value|\\d+\\$[ds]|[ds])#', function ($m) use($rule, $withValue) {
         static $i = -1;
         switch ($m[1]) {
             case 'name':
                 return $rule->control->getName();
             case 'label':
                 return $rule->control->translate($rule->control->caption);
             case 'value':
                 return $withValue ? $rule->control->getValue() : $m[0];
             default:
                 $args = is_array($rule->arg) ? $rule->arg : array($rule->arg);
                 $i = (int) $m[1] ? $m[1] - 1 : $i + 1;
                 return isset($args[$i]) ? $args[$i] instanceof IControl ? $withValue ? $args[$i]->getValue() : "%{$i}" : $args[$i] : '';
         }
     }, $message);
     return $message;
 }
开发者ID:rostenkowski,项目名称:nette,代码行数:31,代码来源:Validator.php


示例13: export

 /** Builds the HTML code to be exported starting from what has been saved in DB
  * @param string $text
  * @return string
  */
 public function export($text)
 {
     $text = preg_replace_callback('/{CCM:CID_([0-9]+)}/i', array('ContentExporter', 'replacePageWithPlaceHolderInMatch'), $text);
     $text = preg_replace_callback('/{CCM:FID_([0-9]+)}/i', array('ContentExporter', 'replaceImageWithPlaceHolderInMatch'), $text);
     $text = preg_replace_callback('/{CCM:FID_DL_([0-9]+)}/i', array('ContentExporter', 'replaceFileWithPlaceHolderInMatch'), $text);
     return $text;
 }
开发者ID:ojalehto,项目名称:concrete5-legacy,代码行数:11,代码来源:content.php


示例14: split

 /**
  * Splits a string by spaces
  * (Strings with quotes will be regarded).
  *
  * Examples:
  * "a b 'c d'"   -> array('a', 'b', 'c d')
  * "a=1 b='c d'" -> array('a' => 1, 'b' => 'c d')
  *
  * @param string $string
  *
  * @return array
  */
 public static function split($string)
 {
     $string = trim($string);
     if (empty($string)) {
         return [];
     }
     $result = [];
     $spacer = '@@@REX_SPACER@@@';
     $quoted = [];
     $pattern = '@(["\'])((?:.*[^\\\\])?(?:\\\\\\\\)*)\\1@Us';
     $callback = function ($match) use($spacer, &$quoted) {
         $quoted[] = str_replace(['\\' . $match[1], '\\\\'], [$match[1], '\\'], $match[2]);
         return $spacer;
     };
     $string = preg_replace_callback($pattern, $callback, $string);
     $parts = preg_split('@\\s+@', $string);
     $i = 0;
     foreach ($parts as $part) {
         $part = explode('=', $part, 2);
         if (isset($part[1])) {
             $value = $part[1] == $spacer ? $quoted[$i++] : $part[1];
             $result[$part[0]] = $value;
         } else {
             $value = $part[0] == $spacer ? $quoted[$i++] : $part[0];
             $result[] = $value;
         }
     }
     return $result;
 }
开发者ID:staabm,项目名称:redaxo,代码行数:41,代码来源:string.php


示例15: eventMethod

 /**
  * Turns an event into a method name, by replacing . and _ with a capital of the following word. For example,
  * if the event is something like user.updating, then the method would become userUpdating.
  *
  * @param string $event
  * @return string
  */
 protected static function eventMethod($event)
 {
     $callback = function ($matches) {
         return strtoupper($matches[1][1]);
     };
     return preg_replace_callback('/([._-][a-z])/i', $callback, $event);
 }
开发者ID:kamaroly,项目名称:shift,代码行数:14,代码来源:Observable.php


示例16: replaceDatePlaceholders

 /**
  * Date placeholder replacement.
  * Replaces %{somevalue} with date({somevalue}).
  *
  * @param  string               $string
  * @param  mixed <integer|null> $time
  * @return string
  */
 public static function replaceDatePlaceholders($string, $time = null)
 {
     $time = $time === null ? time() : $time;
     return preg_replace_callback('#%([a-zA-Z])#', function ($match) use($time) {
         return date($match[1], $time);
     }, $string);
 }
开发者ID:imjerrybao,项目名称:phpbu,代码行数:15,代码来源:Str.php


示例17: getTableName

 /**
  * 得到完整的数据表名
  * 
  * @access public
  * @return string
  */
 public function getTableName()
 {
     if (empty($this->trueTableName)) {
         $tableName = '';
         foreach ($this->viewFields as $key => $view) {
             // 获取数据表名称
             if (isset($view['_table'])) {
                 // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图
                 $tableName .= $view['_table'];
                 $prefix = $this->tablePrefix;
                 $tableName = preg_replace_callback("/__([A-Z_-]+)__/sU", function ($match) use($prefix) {
                     return $prefix . strtolower($match[1]);
                 }, $tableName);
             } else {
                 $class = $key . 'Model';
                 $Model = class_exists($class) ? new $class() : M($key);
                 $tableName .= $Model->getTableName();
             }
             // 表别名定义
             $tableName .= !empty($view['_as']) ? ' ' . $view['_as'] : ' ' . $key;
             // 支持ON 条件定义
             $tableName .= !empty($view['_on']) ? ' ON ' . $view['_on'] : '';
             // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效
             $type = !empty($view['_type']) ? $view['_type'] : '';
             $tableName .= ' ' . strtoupper($type) . ' JOIN ';
             $len = strlen($type . '_JOIN ');
         }
         $tableName = substr($tableName, 0, -$len);
         $this->trueTableName = $tableName;
     }
     return $this->trueTableName;
 }
开发者ID:siimanager,项目名称:sii,代码行数:38,代码来源:ViewModel.class.php


示例18: formatHtml

 public static function formatHtml($mask)
 {
     $args = func_get_args();
     return preg_replace_callback('#%#', function () use(&$args, &$count) {
         return htmlspecialchars($args[++$count], ENT_IGNORE | ENT_QUOTES, 'UTF-8');
     }, $mask);
 }
开发者ID:VasekPurchart,项目名称:khanovaskola-v3,代码行数:7,代码来源:Helpers.php


示例19: _getContent

 private function _getContent($file)
 {
     $file = realpath($file);
     if (!$file || in_array($file, self::$filesIncluded) || false === ($content = @file_get_contents($file))) {
         // file missing, already included, or failed read
         return '';
     }
     self::$filesIncluded[] = realpath($file);
     $this->_currentDir = dirname($file);
     // remove UTF-8 BOM if present
     if (pack("CCC", 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
         $content = substr($content, 3);
     }
     // ensure uniform EOLs
     $content = str_replace("\r\n", "\n", $content);
     // process @imports
     $content = preg_replace_callback('/
             @import\\s+
             (?:url\\(\\s*)?      # maybe url(
             [\'"]?               # maybe quote
             (.*?)                # 1 = URI
             [\'"]?               # maybe end quote
             (?:\\s*\\))?         # maybe )
             ([a-zA-Z,\\s]*)?     # 2 = media list
             ;                    # end token
         /x', array($this, '_importCB'), $content);
     if (self::$_isCss) {
         // rewrite remaining relative URIs
         $content = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array($this, '_urlCB'), $content);
     }
     return $this->_importedContent . $content;
 }
开发者ID:pyropictures,项目名称:wordpress-plugins,代码行数:32,代码来源:ImportProcessor.php


示例20: process

 /**
  * formats the input using the singleTag/closeTag/openTag functions
  *
  * It is auto indenting the whole code, excluding <textarea>, <code> and <pre> tags that must be kept intact.
  * Those tags must however contain only htmlentities-escaped text for everything to work properly.
  * Inline tags are presented on a single line with their content
  *
  * @param Dwoo $dwoo the dwoo instance rendering this
  * @param string $input the xhtml to format
  * @return string formatted xhtml
  */
 public function process($input)
 {
     self::$tabCount = -1;
     // auto indent all but textareas & pre (or we have weird tabs inside)
     $input = preg_replace_callback("#(<[^>]+>)(\\s*)([^<]*)#", array('self', 'tagDispatcher'), $input);
     return $input;
 }
开发者ID:nan0desu,项目名称:xyntach,代码行数:18,代码来源:html_format.php



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP preg_split函数代码示例发布时间:2022-05-15
下一篇:
PHP preg_replace函数代码示例发布时间:2022-05-15
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap