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


PHP preg_match函数代码示例

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


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

示例1: global_filter

/**
 * 全局安全过滤函数
 * 支持SQL注入和跨站脚本攻击
 */
function global_filter()
{
    //APP,ACT 分别为控制器和控制器方法
    $params = array(APP, ACT);
    foreach ($params as $k => $v) {
        if (!preg_match("/^[a-zA-Z0-9_-]+\$/", $v)) {
            header_status_404();
        }
    }
    $arrStr = array('%0d%0a', "'", '<', '>', '$', 'script', 'document', 'eval', 'atestu', 'select', 'insert?into', 'delete?from');
    global_inject_input($_SERVER['HTTP_REFERER'], $arrStr, true);
    global_inject_input($_SERVER['HTTP_USER_AGENT'], $arrStr, true);
    global_inject_input($_SERVER['HTTP_ACCEPT_LANGUAGE'], $arrStr, true);
    global_inject_input($_GET, array_merge($arrStr, array('"')), true);
    //global_inject_input($_COOKIE, array_merge($arrStr, array('"', '&')), true);
    //cookie会有对url的记录(pGClX_last_url)。去掉对&的判断
    global_inject_input($_COOKIE, array_merge($arrStr, array('"')), true);
    global_inject_input($_SERVER, array('%0d%0a'), true);
    //处理跨域POST提交问题
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        //处理客户端POST请求处理没有HTTP_REFERER参数问题
        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = parse_url($_SERVER['HTTP_REFERER']);
            $referer_host = !empty($url['port']) && $url['port'] != '80' ? $url['host'] . ':' . $url['port'] : $url['host'];
            if ($referer_host != $_SERVER['HTTP_HOST']) {
                header_status_404();
            }
        }
    }
    global_inject_input($_POST, array('%0d%0a'));
    global_inject_input($_REQUEST, array('%0d%0a'));
}
开发者ID:w5678912345,项目名称:Web-Security-Filter,代码行数:36,代码来源:security_filter.php

示例2: executeConsole

 public function executeConsole(AgaviRequestDataHolder $request_data)
 {
     $migration_description = $request_data->getParameter('description');
     $migration_timestamp = date('YmdHis');
     $migration_slug = StringToolkit::asSnakeCase(trim($request_data->getParameter('name', 'default')));
     $migration_name = StringToolkit::asStudlyCaps($migration_slug);
     $migration_dir = $this->getAttribute('migration_dir');
     // Bit of a hack to build namespace
     if (!preg_match('#.+/app/(?:modules|migration)/(\\w+_?)(?:$|/.+)#', $migration_dir, $matches)) {
         throw new RuntimeError(sprintf('Could not find namespace info in path %s', $migration_dir));
     }
     $namespace_parts = explode('_', $matches[1]);
     if (count($namespace_parts) == 1) {
         // @todo app migration - introduce a project root namespace setting
         $namespace_parts = ['Your', 'Application'];
     }
     // And a hack to determine the technology namespace
     $target = $request_data->getParameter('target');
     if (strpos($target, 'event_source')) {
         $technology = 'CouchDb';
     } elseif (strpos($target, 'view_store')) {
         $technology = 'Elasticsearch';
     } else {
         $technology = 'RabbitMq';
     }
     $migration_filepath = sprintf('%1$s%2$s%3$s_%4$s%2$s%4$s.php', $migration_dir, DIRECTORY_SEPARATOR, $migration_timestamp, $migration_slug);
     $twig_renderer = TwigRenderer::create(['template_paths' => [__DIR__]]);
     $twig_renderer->renderToFile($technology . 'Migration.tpl.twig', $migration_filepath, ['name' => $migration_name, 'timestamp' => $migration_timestamp, 'description' => $migration_description, 'folder' => $migration_dir, 'filepath' => $migration_filepath, 'vendor_prefix' => $namespace_parts[0], 'package_prefix' => $namespace_parts[1], 'technology' => $technology, 'project_prefix' => AgaviConfig::get('core.project_prefix')]);
     return $this->cliMessage('-> migration template was created here:' . PHP_EOL . $migration_filepath . PHP_EOL);
 }
开发者ID:honeybee,项目名称:honeybee-agavi-cmf-vendor,代码行数:30,代码来源:CreateSuccessView.class.php

示例3: submitInfo

 public function submitInfo()
 {
     $this->load->model("settings_model");
     // Gather the values
     $values = array('nickname' => htmlspecialchars($this->input->post("nickname")), 'location' => htmlspecialchars($this->input->post("location")));
     // Change language
     if ($this->config->item('show_language_chooser')) {
         $values['language'] = $this->input->post("language");
         if (!is_dir("application/language/" . $values['language'])) {
             die("3");
         } else {
             $this->user->setLanguage($values['language']);
             $this->plugins->onSetLanguage($this->user->getId(), $values['language']);
         }
     }
     // Remove the nickname field if it wasn't changed
     if ($values['nickname'] == $this->user->getNickname()) {
         $values = array('location' => $this->input->post("location"));
     } elseif (strlen($values['nickname']) < 4 || strlen($values['nickname']) > 14 || !preg_match("/[A-Za-z0-9]*/", $values['nickname'])) {
         die(lang("nickname_error", "ucp"));
     } elseif ($this->internal_user_model->nicknameExists($values['nickname'])) {
         die("2");
     }
     if (strlen($values['location']) > 32 && !ctype_alpha($values['location'])) {
         die(lang("location_error", "ucp"));
     }
     $this->settings_model->saveSettings($values);
     $this->plugins->onSaveSettings($this->user->getId(), $values);
     die("1");
 }
开发者ID:saqar,项目名称:FusionCMS-themes-and-modules,代码行数:30,代码来源:settings.php

示例4: smarty_validate_criteria_isCCExpDate

/**
 * test if a value is a valid credit card expiration date
 *
 * @param string $value the value being tested
 * @param boolean $empty if field can be empty
 * @param array params validate parameter values
 * @param array formvars form var values
 */
function smarty_validate_criteria_isCCExpDate($value, $empty, &$params, &$formvars)
{
    if (strlen($value) == 0) {
        return $empty;
    }
    if (!preg_match('!^(\\d+)\\D+(\\d+)$!', $value, $_match)) {
        return false;
    }
    $_month = $_match[1];
    $_year = $_match[2];
    if (strlen($_year) == 2) {
        $_year = substr(date('Y', time()), 0, 2) . $_year;
    }
    $_month = (int) $_month;
    $_year = (int) $_year;
    if ($_month < 1 || $_month > 12) {
        return false;
    }
    if (date('Y', time()) > $_year) {
        return false;
    }
    if (date('Y', time()) == $_year && date('m', time()) > $_month) {
        return false;
    }
    return true;
}
开发者ID:ReneVallecillo,项目名称:almidon,代码行数:34,代码来源:validate_criteria.isCCExpDate.php

示例5: PMA_sanitize

/**
 * Sanitizes $message, taking into account our special codes
 * for formatting.
 *
 * If you want to include result in element attribute, you should escape it.
 *
 * Examples:
 *
 * <p><?php echo PMA_sanitize($foo); ?></p>
 *
 * <a title="<?php echo PMA_sanitize($foo, true); ?>">bar</a>
 *
 * @uses    preg_replace()
 * @uses    strtr()
 * @param   string   the message
 * @param   boolean  whether to escape html in result
 *
 * @return  string   the sanitized message
 *
 * @access  public
 */
function PMA_sanitize($message, $escape = false, $safe = false)
{
    if (!$safe) {
        $message = strtr($message, array('<' => '&lt;', '>' => '&gt;'));
    }
    $replace_pairs = array('[i]' => '<em>', '[/i]' => '</em>', '[em]' => '<em>', '[/em]' => '</em>', '[b]' => '<strong>', '[/b]' => '</strong>', '[strong]' => '<strong>', '[/strong]' => '</strong>', '[tt]' => '<code>', '[/tt]' => '</code>', '[code]' => '<code>', '[/code]' => '</code>', '[kbd]' => '<kbd>', '[/kbd]' => '</kbd>', '[br]' => '<br />', '[/a]' => '</a>', '[sup]' => '<sup>', '[/sup]' => '</sup>');
    $message = strtr($message, $replace_pairs);
    $pattern = '/\\[a@([^"@]*)@([^]"]*)\\]/';
    if (preg_match_all($pattern, $message, $founds, PREG_SET_ORDER)) {
        $valid_links = array('http', './Do', './ur');
        foreach ($founds as $found) {
            // only http... and ./Do... allowed
            if (!in_array(substr($found[1], 0, 4), $valid_links)) {
                return $message;
            }
            // a-z and _ allowed in target
            if (!empty($found[2]) && preg_match('/[^a-z_]+/i', $found[2])) {
                return $message;
            }
        }
        if (substr($found[1], 0, 4) == 'http') {
            $message = preg_replace($pattern, '<a href="' . PMA_linkURL($found[1]) . '" target="\\2">', $message);
        } else {
            $message = preg_replace($pattern, '<a href="\\1" target="\\2">', $message);
        }
    }
    if ($escape) {
        $message = htmlspecialchars($message);
    }
    return $message;
}
开发者ID:dingdong2310,项目名称:g5_theme,代码行数:52,代码来源:sanitizing.lib.php

示例6: __call

 public function __call($s_method_name, $arr_arguments)
 {
     if (!method_exists($this, $s_method_name)) {
         // если еще не имлементировали
         $s_match = "";
         $s_method_prefix = '';
         $s_method_base = '';
         $arr_matches = array();
         $bSucc = preg_match("/[A-Z_]/", $s_method_name, $arr_matches);
         if ($bSucc) {
             $s_match = $arr_matches[0];
             $i_match = strpos($s_method_name, $s_match);
             $s_method_prefix = substr($s_method_name, 0, $i_match) . "/";
             $s_method_base = substr($s_method_name, 0, $i_match + ($s_match === "_" ? 1 : 0));
         }
         $s_class_enter = "__" . $s_method_name;
         // метод, общий для всех режимов
         if (!class_exists($s_class_enter)) {
             $s_entermethod_lib = "methods/" . $s_method_prefix . "__" . $s_method_name . ".lib.php";
             $this->__loadLib($s_entermethod_lib);
             $this->__implement($s_class_enter);
         }
         $s_class_mode = "__" . $s_method_name . "_";
         // метод, выбираемый в зависимости от режима
         if (!class_exists($s_class_mode)) {
             $s_modemethod_lib = "methods/" . $s_method_prefix . "__" . $s_method_name . "_" . cmsController::getInstance()->getCurrentMode() . ".lib.php";
             $this->__loadLib($s_modemethod_lib);
             $this->__implement($s_class_mode);
         }
     }
     return parent::__call($s_method_name, $arr_arguments);
 }
开发者ID:tomoonshine,项目名称:postsms,代码行数:32,代码来源:class+из+content.php

示例7: getLinkDefsInFieldMeta

 /**
  * Get link definition defined in 'fields' metadata. In linkDefs can be used as value (e.g. "type": "hasChildren") and/or variables (e.g. "entityName":"{entity}"). Variables should be defined into fieldDefs (in 'entityDefs' metadata).
  *
  * @param  string $entityName
  * @param  array  $fieldDef
  * @param  array  $linkFieldDefsByType
  * @return array | null
  */
 public function getLinkDefsInFieldMeta($entityName, $fieldDef, array $linkFieldDefsByType = null)
 {
     if (!isset($fieldDefsByType)) {
         $fieldDefsByType = $this->getFieldDefsByType($fieldDef);
         if (!isset($fieldDefsByType['linkDefs'])) {
             return null;
         }
         $linkFieldDefsByType = $fieldDefsByType['linkDefs'];
     }
     foreach ($linkFieldDefsByType as $paramName => &$paramValue) {
         if (preg_match('/{(.*?)}/', $paramValue, $matches)) {
             if (in_array($matches[1], array_keys($fieldDef))) {
                 $value = $fieldDef[$matches[1]];
             } else {
                 if (strtolower($matches[1]) == 'entity') {
                     $value = $entityName;
                 }
             }
             if (isset($value)) {
                 $paramValue = str_replace('{' . $matches[1] . '}', $value, $paramValue);
             }
         }
     }
     return $linkFieldDefsByType;
 }
开发者ID:chinazan,项目名称:zzcrm,代码行数:33,代码来源:Helper.php

示例8: validatePassword

 public static function validatePassword(User $user, $value)
 {
     $length = strlen($value);
     $config = $user->getMain()->getConfig();
     $minLength = $config->getNested("Registration.MinLength", 4);
     if ($length < $minLength) {
         $user->getPlayer()->sendMessage($config->getNested("Messages.Register.PasswordUnderflow", "too short"));
         return false;
     }
     $maxLength = $config->getNested("Registration.MaxLength", -1);
     if ($maxLength !== -1 and $length > $maxLength) {
         $user->getPlayer()->sendMessage($config->getNested("Messages.Register.PasswordOverflow", "too long"));
         return false;
     }
     if ($config->getNested("Registration.BanPureLetters", false) and preg_match('/^[a-z]+$/i', $value)) {
         $user->getPlayer()->sendMessage($config->getNested("Messages.Register.PasswordPureLetters", "only letters"));
         return false;
     }
     if ($config->getNested("Registration.BanPureNumbers", false) and preg_match('/^[0-9]+$/', $value)) {
         $user->getPlayer()->sendMessage($config->getNested("Messages.Register.PasswordPureNumbers", "only numbers"));
         return false;
     }
     if ($config->getNested("Registration.DisallowSlashes", true) and $value[0] === "/") {
         $user->getPlayer()->sendMessage($config->getNested("Messages.Register.PasswordSlashes", "do not start with slashes"));
         return false;
     }
     return true;
 }
开发者ID:GoneTone,项目名称:HereAuth,代码行数:28,代码来源:PasswordInputRegistrationStep.php

示例9: getImageHtml

 /**
  * Constructs HTML for the tutorial (laboriously), including an imagemap for the clickable "Help desk" button.
  *
  * @param MediaTransformOutput $thumb
  * @param String|null $campaign Upload Wizard campaign for which the tutorial should be displayed.
  *
  * @return String HTML representing the image, with clickable helpdesk button
  */
 public static function getImageHtml(MediaTransformOutput $thumb, $campaign = null)
 {
     $helpDeskUrl = wfMessage('mwe-upwiz-help-desk-url')->text();
     // Per convention, we may be either using an absolute URL or a wiki page title in this UI message
     if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $helpDeskUrl)) {
         $helpDeskHref = $helpDeskUrl;
     } else {
         $helpDeskTitle = Title::newFromText($helpDeskUrl);
         $helpDeskHref = $helpDeskTitle ? $helpDeskTitle->getLocalURL() : '#';
     }
     $buttonCoords = UploadWizardConfig::getSetting('tutorialHelpdeskCoords', $campaign);
     $useMap = $buttonCoords !== false && trim($buttonCoords) != '';
     $imgAttributes = array('src' => $thumb->getUrl(), 'width' => $thumb->getWidth(), 'height' => $thumb->getHeight());
     if ($useMap) {
         $imgAttributes['usemap'] = '#' . self::IMAGEMAP_ID;
     }
     // here we use the not-yet-forgotten HTML imagemap to add a clickable area to the tutorial image.
     // we could do more special effects with hovers and images and such, not to mention SVG scripting,
     // but we aren't sure what we want yet...
     $imgHtml = Html::element('img', $imgAttributes);
     if ($useMap) {
         $areaAltText = wfMessage('mwe-upwiz-help-desk')->text();
         $area = Html::element('area', array('shape' => 'rect', 'coords' => $buttonCoords, 'href' => $helpDeskHref, 'alt' => $areaAltText, 'title' => $areaAltText));
         $imgHtml = Html::rawElement('map', array('id' => self::IMAGEMAP_ID, 'name' => self::IMAGEMAP_ID), $area) . $imgHtml;
     }
     return $imgHtml;
 }
开发者ID:JeroenDeDauw,项目名称:UploadWizard,代码行数:35,代码来源:UploadWizardTutorial.php

示例10: created_on

 public function created_on()
 {
     if (preg_match('/Created On :[\\s]+(.*?)\\n/', $this->body, $match)) {
         return strtotime($match[1]);
     }
     return null;
 }
开发者ID:jinguanio,项目名称:whois,代码行数:7,代码来源:namebay.php

示例11: preProcessing

 public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type)
 {
     $params = $compiler->getCompiledParams($params);
     $parsedParams = array();
     if (!isset($params['*'])) {
         $params['*'] = array();
     }
     foreach ($params['*'] as $param => $defValue) {
         if (is_numeric($param)) {
             $param = $defValue;
             $defValue = null;
         }
         $param = trim($param, '\'"');
         if (!preg_match('#^[a-z0-9_]+$#i', $param)) {
             throw new Dwoo_Compilation_Exception($compiler, 'Function : parameter names must contain only A-Z, 0-9 or _');
         }
         $parsedParams[$param] = $defValue;
     }
     $params['name'] = substr($params['name'], 1, -1);
     $params['*'] = $parsedParams;
     $params['uuid'] = uniqid();
     $compiler->addTemplatePlugin($params['name'], $parsedParams, $params['uuid']);
     $currentBlock =& $compiler->getCurrentBlock();
     $currentBlock['params'] = $params;
     return '';
 }
开发者ID:netfreak,项目名称:pyrocms,代码行数:26,代码来源:template.php

示例12: filtre_picture

/**
 * On modifie les URLS des images dans le corps de l'article
 */
function filtre_picture($content, $url, $id)
{
    $matches = array();
    $processing_pictures = array();
    // list of processing image to avoid processing the same pictures twice
    preg_match_all('#<\\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER);
    foreach ($matches as $i => $link) {
        $link[1] = trim($link[1]);
        if (!preg_match('#^(([a-z]+://)|(\\#))#', $link[1])) {
            $absolute_path = get_absolute_link($link[2], $url);
            $filename = basename(parse_url($absolute_path, PHP_URL_PATH));
            $directory = create_assets_directory($id);
            $fullpath = $directory . '/' . $filename;
            if (in_array($absolute_path, $processing_pictures) === true) {
                // replace picture's URL only if processing is OK : already processing -> go to next picture
                continue;
            }
            if (download_pictures($absolute_path, $fullpath) === true) {
                $content = str_replace($matches[$i][2], $fullpath, $content);
            }
            $processing_pictures[] = $absolute_path;
        }
    }
    return $content;
}
开发者ID:akoenig,项目名称:wallabag,代码行数:28,代码来源:pochePictures.php

示例13: actionIndex

 public function actionIndex()
 {
     if (isset($_GET['id'])) {
         $model = Document::model()->findByPk($_GET['id']);
         $this->render('detail', array('model' => $model));
         $cfg = (require dirname(__FILE__) . '/../../config/main.php');
         //print '<pre>';
         //print_r($cfg['components']['db']);
         if (preg_match("/^mysql:host=(\\w.*);dbname=(\\w.*)/i", $cfg['components']['db']['connectionString'], $match)) {
             //print_r($match);
         }
         //$db_name = "myphotos";
         //$db_server = "localhost";
         //$db_user = "root";
         //$db_pass = "";
         $db_name = $match[2];
         $db_server = $match[1];
         $db_user = $cfg['components']['db']["username"];
         $db_pass = $cfg['components']['db']["password"];
         $sql = "UPDATE gs_document SET counter=counter+1 WHERE doc_id='" . $_GET['id'] . "'";
         //print $sql;
         //$command = Yii::app()->db->createCommand($sql);
         //$command->execute();
         $dbh = new PDO('mysql:host=' . $db_server . ';port=3306;dbname=' . $db_name, $db_user, $db_pass, array(PDO::ATTR_PERSISTENT => false));
         $stmt = $dbh->prepare($sql);
         $stmt->execute();
     } else {
         $criteria = new CDbCriteria();
         $criteria->select = '*';
         $criteria->condition = 'status = 1';
         $criteria->order = 'sort_order ASC ,last_update DESC';
         $model = Document::model()->findAll($criteria);
         $this->render('index', array('model' => $model));
     }
 }
开发者ID:ultr4h4ck,项目名称:project_gspa,代码行数:35,代码来源:DocumentController.php

示例14: getTangentText

function getTangentText($type, $keyword)
{
    global $dbHost, $dbUser, $dbPassword, $dbName;
    $link = @mysql_connect($dbHost, $dbUser, $dbPassword);
    if (!$link) {
        die("Cannot connect : " . mysql_error());
    }
    if (!@mysql_select_db($dbName, $link)) {
        die("Cannot find database : " . mysql_error());
    }
    $result = mysql_query("SELECT sr_keywords, sr_text FROM soRandom WHERE sr_type = '" . $type . "' ORDER BY sr_ID ASC;", $link);
    $tempCounter = 0;
    while ($row = mysql_fetch_assoc($result)) {
        $pKey = "/" . $keyword . "/";
        $pos = preg_match($pKey, $row['sr_keywords']);
        //echo $pos . " is pos<br>";
        //echo $keyword;
        //echo " is keyword and this is the search return: " . $row['keywords'];
        if ($pos != 0) {
            $text[$tempCounter] = stripslashes($row["sr_text"]);
            $tempCounter++;
        }
    }
    mysql_close($link);
    //$text=htmlentities($text);
    return $text;
}
开发者ID:ui-libraries,项目名称:TIRW,代码行数:27,代码来源:includes.php

示例15: wpcf7_submit_shortcode_handler

function wpcf7_submit_shortcode_handler($tag)
{
    if (!is_array($tag)) {
        return '';
    }
    $options = (array) $tag['options'];
    $values = (array) $tag['values'];
    $atts = '';
    $id_att = '';
    $class_att = '';
    foreach ($options as $option) {
        if (preg_match('%^id:([-0-9a-zA-Z_]+)$%', $option, $matches)) {
            $id_att = $matches[1];
        } elseif (preg_match('%^class:([-0-9a-zA-Z_]+)$%', $option, $matches)) {
            $class_att .= ' ' . $matches[1];
        }
    }
    if ($id_att) {
        $atts .= ' id="' . trim($id_att) . '"';
    }
    if ($class_att) {
        $atts .= ' class="' . trim($class_att) . '"';
    }
    $value = $values[0];
    if (empty($value)) {
        $value = __('Send', 'wpcf7');
    }
    $ajax_loader_image_url = wpcf7_plugin_url('images/ajax-loader.gif');
    $html = '<input type="submit" value="' . esc_attr($value) . '"' . $atts . ' />';
    $html .= ' <img class="ajax-loader" style="visibility: hidden;" alt="ajax loader" src="' . $ajax_loader_image_url . '" />';
    return $html;
}
开发者ID:alanhogan,项目名称:contact-form-8,代码行数:32,代码来源:submit.php


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