本文整理汇总了PHP中preg_grep函数的典型用法代码示例。如果您正苦于以下问题:PHP preg_grep函数的具体用法?PHP preg_grep怎么用?PHP preg_grep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了preg_grep函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: scan_dir_files
function scan_dir_files($logsdir, $wildcard, $subdir_wildcard, $write_dir, $dbhost, $dbport, $dbuser, $dbpass, $processid)
{
if (!file_exists($logsdir)) {
echo "Dir: " . $logsdir . " does not exist\n";
exit(1);
}
$dirHandle = opendir("{$logsdir}");
//List files in images directory
while (($file = readdir($dirHandle)) !== false) {
$file_list[] = $file;
}
closedir($dirHandle);
$filtered_file_list = preg_grep($wildcard, $file_list);
if (count($filtered_file_list) > 0) {
$files_to_retrieve = filter_file_list($filtered_file_list, $processid, $dbhost, $dbport, $dbuser, $dbpass);
foreach ($files_to_retrieve as $file) {
echo "Copying " . $file . "\n";
copy($logsdir . '/' . $file, $write_dir . '/' . $file);
}
} else {
echo "No files to copy from the logs dir(" . $logsdir . ").\n";
}
$filtered_subdir_list = preg_grep($subdir_wildcard, $file_list);
foreach ($filtered_subdir_list as $subdir) {
if (is_dir($logsdir . "/" . $subdir)) {
echo "Scanning " . $subdir . "\n";
scan_dir_files($logsdir . "/" . $subdir, $wildcard, $subdir_wildcard, $write_dir, $dbhost, $dbport, $dbuser, $dbpass, $processid);
}
}
}
示例2: getBodyHighlighted
public function getBodyHighlighted($keywords = null, $wordsAround = 5, $tag = '<b>', $delimiter = ' … ', $maxMatchesNum = NULL)
{
if (!is_array($keywords)) {
$keywords = preg_replace('/<.*>/Uu', '', $keywords);
$keywords = preg_replace('/\\s+/u', ' ', $keywords);
$keywords = preg_split('/\\s+/u', $keywords, -1, PREG_SPLIT_NO_EMPTY);
}
$tag_close = preg_replace('/<([a-z0-9]+).*>/isx', '</$1>', $tag);
array_walk($keywords, 'preg_quote');
$words = preg_split('/\\s+/u', strip_tags($this->data['BODY']), -1, PREG_SPLIT_NO_EMPTY);
if (!($matched = preg_grep("/(" . join('|', $keywords) . ")/iu", $words))) {
return false;
}
foreach ($matched as $i => $word) {
$words[$i] = "{$tag}{$words[$i]}{$tag_close}";
}
$matches = array();
$prev = -$wordsAround * 2;
foreach ($matched as $i => $word) {
if ($i - $wordsAround > $prev) {
$start = $i - $wordsAround;
if ($start < 0) {
$start = 0;
}
$matches[] = join(' ', array_slice($words, $start, $wordsAround * 2 + 1));
}
$prev = $i;
}
if ($maxMatchesNum) {
$matches = array_slice($matches, 0, $maxMatchesNum);
}
return join($delimiter, $matches);
}
示例3: getConfigTreeBuilder
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('hearsay_require_js');
$rootNode->children()->scalarNode('require_js_src')->cannotBeEmpty()->defaultValue('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js')->end()->scalarNode('initialize_template')->cannotBeEmpty()->defaultValue('HearsayRequireJSBundle::initialize.html.twig')->end()->scalarNode('base_url')->defaultValue('js')->end()->scalarNode('base_dir')->isRequired()->cannotBeEmpty()->end()->arrayNode('paths')->defaultValue(array())->useAttributeAsKey('path')->normalizeKeys(false)->prototype('array')->beforeNormalization()->ifString()->then(function ($v) {
return array('location' => $v);
})->end()->children()->variableNode('location')->isRequired()->cannotBeEmpty()->validate()->always(function ($v) {
if (!is_string($v) && !is_array($v)) {
throw new InvalidTypeException();
}
$vs = !is_array($v) ? (array) $v : $v;
$er = preg_grep('~\\.js$~', $vs);
if ($er) {
throw new InvalidPathException();
}
return $v;
})->end()->end()->booleanNode('external')->cannotBeEmpty()->defaultFalse()->end()->end()->end()->end()->arrayNode('shim')->defaultValue(array())->useAttributeAsKey('name')->normalizeKeys(false)->prototype('array')->children()->arrayNode('deps')->defaultValue(array())->prototype('scalar')->end()->end()->scalarNode('exports')->end()->end()->end()->end()->arrayNode('options')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->beforeNormalization()->always(function ($v) {
return array('value' => $v);
})->end()->children()->variableNode('value')->isRequired()->end()->end()->end()->end()->arrayNode('optimizer')->children()->scalarNode('path')->isRequired()->cannotBeEmpty()->end()->booleanNode('hide_unoptimized_assets')->defaultFalse()->end()->booleanNode('declare_module_name')->defaultFalse()->end()->arrayNode('exclude')->defaultValue(array())->prototype('scalar')->end()->end()->arrayNode('modules')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->children()->scalarNode('name')->cannotBeEmpty()->end()->arrayNode('include')->defaultValue(array())->prototype('scalar')->end()->end()->arrayNode('exclude')->defaultValue(array())->prototype('scalar')->end()->end()->end()->end()->end()->arrayNode('options')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->beforeNormalization()->always(function ($v) {
return array('value' => $v);
})->end()->children()->variableNode('value')->isRequired()->end()->end()->end()->end()->scalarNode('timeout')->cannotBeEmpty()->validate()->ifTrue(function ($v) {
return !(is_int($v) || ctype_digit($v));
})->thenInvalid('Invalid number of seconds "%s"')->end()->defaultValue(60)->end()->scalarNode('almond_path')->defaultFalse()->end()->end()->end()->end();
return $treeBuilder;
}
示例4: df_browse_cache
function df_browse_cache()
{
global $db, $prefix;
$cached = array('config' => array(), 'themes' => array(), 'modules' => array());
$dir = str_replace(BASEDIR . 'cache/', '', glob(BASEDIR . 'cache/*.{php,inc}', GLOB_BRACE));
# get all configuration files
# core files should have its own formatting
# all cached files should be lower case
# modules configuration files should go under the module files list, not under core config list
$pattern = array('/^(a_|bb_|config_|installer)([a-z\\-_]+[^\\.])\\.php/i');
$replace = array('$1$2');
$tmp = preg_replace($pattern, $replace, preg_grep('/^(a_|bb_|config_|installer_)/i', $dir));
foreach ($tmp as $key => $file) {
$GLOBALS['cpgtpl']->assign_block_vars('config', array('S_FILE' => $file));
}
$tmp = array_unique(preg_replace('/^tpl_([a-z0-9\\-_]+)_[a-z0-9\\-_].*+/i', '$1', preg_grep('/^tpl_/i', $dir)));
foreach ($tmp as $key => $file) {
$GLOBALS['cpgtpl']->assign_block_vars('themes', array('S_FILE' => $file));
}
//$Module = new Module;
//$modules = implode('|', arrayRebuild($Module->list, array('title')));
$modules = array();
$result = $db->sql_query('SELECT title FROM ' . $prefix . '_modules');
while ($row = $db->sql_fetchrow($result, SQL_NUM)) {
$modules[] = $row[0];
}
$db->free_result($result);
$modules = implode('|', $modules);
$tmp = array_unique(preg_replace('/^(' . $modules . ')_.*/i', '$1', preg_grep('/^(' . $modules . ')/i', $dir)));
foreach ($tmp as $key => $file) {
$GLOBALS['cpgtpl']->assign_block_vars('modules', array('S_FILE' => $file, 'U_DEL' => URL::admin("cache&module={$file}&delete")));
}
unset($dir, $modules, $tmp);
}
示例5: getAvailableSetFiles
/**
* Return all available sets
* @return array
*/
public function getAvailableSetFiles()
{
$strDir = TL_ROOT . '/web/bundles/contaoddadvancedclasses/sets/';
$arrFiles = preg_grep('~\\.(json)$~', scandir($strDir));
$arrFiles = array_combine($arrFiles, $arrFiles);
return $arrFiles;
}
示例6: buildAttributes
function buildAttributes()
{
$this->fieldnames = array();
$this->attributes = array();
$email = null;
// First let's find the email field.
// First we'll check to see if any fields have been explicitly
// flagged as email address fields.
foreach ($this->table->fields(false, true) as $field) {
if (@$field['email']) {
$email = $field['name'];
break;
}
}
if (!isset($email)) {
// Next lets see if any of the fields actually contain the word
// email in the name
$candidates = preg_grep('/(email)/i', array_keys($this->table->fields()));
foreach ($candidates as $candidate) {
if ($this->table->isChar($candidate)) {
$email = $candidate;
break;
}
}
}
if (isset($email)) {
$field =& $this->table->getField($email);
$this->attributes['email'] =& $field;
unset($field);
$this->fieldnames['email'] = $email;
}
return true;
}
示例7: wpcf7_akismet_submitted_params
function wpcf7_akismet_submitted_params()
{
$params = array('author' => '', 'author_email' => '', 'author_url' => '');
$content = '';
$fes = wpcf7_scan_shortcode();
foreach ($fes as $fe) {
if (!isset($fe['name']) || !isset($_POST[$fe['name']])) {
continue;
}
$value = $_POST[$fe['name']];
if (is_array($value)) {
$value = implode(', ', wpcf7_array_flatten($value));
}
$value = trim($value);
$options = (array) $fe['options'];
if (preg_grep('%^akismet:author$%', $options)) {
$params['author'] = trim($params['author'] . ' ' . $value);
} elseif (preg_grep('%^akismet:author_email$%', $options)) {
if ('' == $params['author_email']) {
$params['author_email'] = $value;
}
} elseif (preg_grep('%^akismet:author_url$%', $options)) {
if ('' == $params['author_url']) {
$params['author_url'] = $value;
}
}
$content = trim($content . "\n\n" . $value);
}
$params = array_filter($params);
if (!$params) {
return false;
}
$params['content'] = $content;
return $params;
}
示例8: handle
/**
* Handle the match
*/
function handle($match, $state, $pos, &$handler)
{
switch ($state) {
case DOKU_LEXER_ENTER:
$data = strtolower(trim(substr($match, strpos($match, ' '), -1)));
return array($state, $data);
case DOKU_LEXER_UNMATCHED:
// check if $match is a == header ==
$headerMatch = preg_grep('/([ \\t]*={2,}[^\\n]+={2,}[ \\t]*(?=))/msSi', array($match));
if (empty($headerMatch)) {
$handler->_addCall('cdata', array($match), $pos);
} else {
// if it's a == header ==, use the core header() renderer
// (copied from core header() in inc/parser/handler.php)
$title = trim($match);
$level = 7 - strspn($title, '=');
if ($level < 1) {
$level = 1;
}
$title = trim($title, '=');
$title = trim($title);
$handler->_addCall('header', array($title, $level, $pos), $pos);
}
return false;
case DOKU_LEXER_EXIT:
return array($state, '');
}
return false;
}
示例9: fast_array_key_filter
public static function fast_array_key_filter($array, $pattern)
{
$pattern = '/' . preg_quote($pattern) . '/';
$keys = preg_grep($pattern, array_keys($array));
$retArray = array_flip($keys);
return array_intersect_key($array, $retArray);
}
示例10: viewdirtree
/**
* viewdirtree()
*
* @param mixed $dir
* @param mixed $currentpath
* @return
*/
function viewdirtree($dir, $currentpath)
{
global $array_dirname, $global_config, $module_file;
$pattern = !empty($dir) ? '/^(' . nv_preg_quote($dir) . ')\\/([^\\/]+)$/' : '/^([^\\/]+)$/';
$_dirlist = preg_grep($pattern, array_keys($array_dirname));
$content = '';
foreach ($_dirlist as $_dir) {
$check_allow_upload_dir = nv_check_allow_upload_dir($_dir);
if (!empty($check_allow_upload_dir)) {
$class_li = ($_dir == $currentpath or strpos($currentpath, $_dir . '/') !== false) ? 'open collapsable' : 'expandable';
$style_color = $_dir == $currentpath ? ' style="color:red"' : '';
$tree = array();
$tree['class1'] = $class_li;
$tree['class2'] = nv_set_dir_class($check_allow_upload_dir) . ' pos' . nv_string_to_filename($dir);
$tree['style'] = $style_color;
$tree['title'] = $_dir;
$tree['titlepath'] = basename($_dir);
$content2 = viewdirtree($_dir, $currentpath);
$xtpl = new XTemplate('foldlist.tpl', NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/modules/' . $module_file);
$xtpl->assign('DIRTREE', $tree);
if (empty($content2)) {
$content2 = '<li class="hide"> </li>';
}
if (!empty($content2)) {
$xtpl->assign('TREE_CONTENT', $content2);
$xtpl->parse('tree.tree_content');
}
$xtpl->parse('tree');
$content .= $xtpl->text('tree');
}
}
return $content;
}
示例11: render_instance
public static function render_instance(BlockInstance $instance, $editing = false)
{
global $THEME;
$configdata = $instance->get('configdata');
if (!isset($configdata['license'])) {
return '';
}
$licensetype = reset(preg_grep('/^([a-z\\-]+)$/', array($configdata['license'])));
if (isset($configdata['version'])) {
$licenseversion = get_string('version' . $configdata['version'], 'blocktype.creativecommons');
} else {
$licenseversion = get_string('version30', 'blocktype.creativecommons');
}
$licenseurl = "http://creativecommons.org/licenses/{$licensetype}/{$licenseversion}/";
$view = $instance->get_view();
$workname = '<span rel="dc:type" href="http://purl.org/dc/dcmitype/Text" property="dc:title">' . $view->display_title(true, false, false) . '</span>';
$authorurl = $view->owner_link();
$authorname = hsc($view->formatted_owner());
$licensename = get_string('cclicensename', 'blocktype.creativecommons', get_string($licensetype, 'blocktype.creativecommons'), $licenseversion);
$licenselink = '<a rel="license" href="' . $licenseurl . '">' . $licensename . '</a>';
$attributionlink = '<a rel="cc:attributionURL" property="cc:attributionName" href="' . $authorurl . '">' . $authorname . '</a>';
$licensestatement = get_string('cclicensestatement', 'blocktype.creativecommons', $workname, $attributionlink, $licenselink);
$permissionlink = '<a rel="cc:morePermissions" href="' . $authorurl . '">' . $authorname . '</a>';
$otherpermissions = get_string('otherpermissions', 'blocktype.creativecommons', $permissionlink);
$smarty = smarty_core();
$smarty->assign('licenseurl', $licenseurl);
$smarty->assign('licenselogo', $THEME->get_image_url($licensetype . '-3_0', 'blocktype/creativecommons'));
$smarty->assign('licensestatement', $licensestatement);
$smarty->assign('otherpermissions', $otherpermissions);
return $smarty->fetch('blocktype:creativecommons:statement.tpl');
}
示例12: run
/**
* Standard modular run function for OcCLE hooks.
*
* @param array The options with which the command was called
* @param array The parameters with which the command was called
* @param object A reference to the OcCLE filesystem object
* @return array Array of stdcommand, stdhtml, stdout, and stderr responses
*/
function run($options, $parameters, &$occle_fs)
{
if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
return array('', do_command_help('grep', array('h'), array(true, true)), '', '');
} else {
if (!array_key_exists(0, $parameters)) {
return array('', '', '', do_lang('MISSING_PARAM', '1', 'grep'));
}
if (!array_key_exists(1, $parameters)) {
return array('', '', '', do_lang('MISSING_PARAM', '2', 'grep'));
} else {
$parameters[1] = $occle_fs->_pwd_to_array($parameters[1]);
}
if (!$occle_fs->_is_file($parameters[1])) {
return array('', '', '', do_lang('NOT_A_FILE', '2'));
}
$_lines = unixify_line_format($occle_fs->read_file($parameters[1]));
$lines = explode("\n", $_lines);
if ($parameters[0] == '' || $parameters[0][0] != '#' && $parameters[0][0] != '/') {
$parameters[0] = '#' . $parameters[0] . '#';
}
$matches = preg_grep($parameters[0], $lines);
$output = '';
foreach ($matches as $value) {
$output .= $value . "\n";
}
return array('', '', $output, '');
}
}
示例13: template_redirect
/**
* Unset the X-Pingback HTTP header.
*
* @hook
*
* @priority 20
*/
public function template_redirect()
{
$headers = headers_list();
if (preg_grep('/X-Pingback:/', $headers)) {
header_remove('X-Pingback');
}
}
示例14: send
public function send(SendGrid\Email $email)
{
$fields = $email->toWebFormat();
$headers = array();
if ("credentials" == $this->method) {
$fields['api_user'] = $this->username;
$fields['api_key'] = $this->password;
} else {
$headers = array('Authorization' => 'Bearer ' . $this->apikey);
}
$files = preg_grep('/files/', array_keys($fields));
foreach ($files as $k => $file) {
$fields[$file] = file_get_contents(substr($fields[$file], 1));
}
$data = array('body' => $fields);
if (count($headers)) {
$data['headers'] = $headers;
}
$response = wp_remote_post(self::URL, $data);
if (!is_array($response) or !isset($response['body'])) {
return false;
}
if ("success" == json_decode($response['body'])->message) {
return true;
}
return false;
}
示例15: getBanksAutoCompleteArray
/**
* Метод возвращает название банка и его идентификатор,
* фильтруя по первым набранных символам
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getBanksAutoCompleteArray(Request $request)
{
$validator = Validator::make($request->all(), ['item' => 'required|string|max:255']);
if ($validator->fails()) {
$error = $validator->errors()->all();
return response()->json(['error' => true, $error]);
}
$term = $request->get('item');
$query = \DB::table('banks')->select('title', 'id')->where('publish', '=', 1)->get();
/**
* дальше идут манипуляции с объектом ответа
* для того, чтобы представить его
* в нужном формате, возможно
* можно сделать оптимальнее
*/
foreach ($query as $q) {
$tempArray[] = $q->title;
}
// Шаблон рег. выражения
$pattern = '/' . preg_quote($term) . '/iu';
// ф-я возвращает массив совпадений
$resultArrayBanks = preg_grep($pattern, $tempArray);
$id = \DB::table('banks')->select('url')->where('publish', '=', 1)->whereIn('title', $resultArrayBanks)->get();
$i = 0;
foreach ($resultArrayBanks as $resultArrayBank) {
$id[$i]->title = $resultArrayBank;
$i++;
}
return \Response::json($id);
}