本文整理汇总了PHP中substr_replace函数的典型用法代码示例。如果您正苦于以下问题:PHP substr_replace函数的具体用法?PHP substr_replace怎么用?PHP substr_replace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了substr_replace函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: filterValue
/**
* @param mixed $value
* @return mixed
*/
public function filterValue($value)
{
$lengthValue = strlen($value);
// Calc the number of chars to replace
$percentage = $this->getConfigPercent();
// Check if we have to replace anything at all
if ($percentage == 0) {
return $value;
}
$numReplaceChars = $lengthValue / (100 / $percentage);
$numReplaceChars = round($numReplaceChars);
// If there are no chars to be replaced return
if ($numReplaceChars == 0) {
return $value;
}
// Calc the char pos to start with
$start = round(($lengthValue - $numReplaceChars) / 2);
// Generate the mask
$mask = str_repeat(self::MASK_CHAR, $numReplaceChars);
if ($numReplaceChars == $lengthValue) {
$start = 0;
}
// Replace the calculated part with mask
$maskedNumber = substr_replace($value, $mask, $start, $numReplaceChars);
return $maskedNumber;
}
开发者ID:radomirz,项目名称:PHP-SDK,代码行数:30,代码来源:MaskValue.php
示例2: script_loader_tag
public function script_loader_tag($tag, $handle, $src)
{
if (!is_ssl() || $this->is_same_origin($src)) {
return $tag;
}
$parsed_url = wp_parse_url($src);
// Bad URL.
if (!isset($parsed_url['host'])) {
return $tag;
}
// @todo Retest google maps... Doesn't seem like it should be a problem.
// @todo Filterable list of domains to ignore?
if ('fonts.googleapis.com' === $parsed_url['host'] || 'maps.googleapis.com' === $parsed_url['host']) {
return $tag;
}
// Null or string.
if (!($metadata = $this->meta->get($src))) {
$this->maybe_add_to_queue($src);
return $tag;
}
$integrity_string = sprintf(' integrity="%s" crossorigin="anonymous"', esc_attr($metadata));
/**
* To insert just after the opening tag.
*
* @todo Breaks if you use wp_add_inline_script( '*', '*', 'before' ).
*/
$pos = 0 === strpos($tag, '<script') ? 7 : 5;
return substr_replace($tag, $integrity_string, $pos, 0);
}
开发者ID:ssnepenthe,项目名称:homonoia,代码行数:29,代码来源:class-sri-injector.php
示例3: autoload
public static function autoload($class)
{
$filename = self::_autoloaderClassToFile($class);
if (!$filename) {
return false;
}
$proLocation = substr_replace(BETTER_ANALYTICS_PLUGIN_DIR, '-pro', -1);
$allowed = false;
if (file_exists($proLocation . $filename)) {
$betterAnalyticsInternal = get_transient('ba_int');
if (@$betterAnalyticsInternal['v'] || strpos(@$_SERVER['SCRIPT_NAME'], '/plugins.php') !== false || strpos(@$_SERVER['SCRIPT_NAME'], '/tools.php') !== false || $class == 'DigitalPointBetterAnalytics_Helper_Api') {
$allowed = true;
}
}
if ($allowed) {
include $proLocation . $filename;
return class_exists($class, false) || interface_exists($class, false);
}
$ecommerceLocation = substr_replace(BETTER_ANALYTICS_PLUGIN_DIR, '-ecommerce', -1);
if (file_exists($ecommerceLocation . $filename)) {
include $ecommerceLocation . $filename;
return class_exists($class, false) || interface_exists($class, false);
} elseif (file_exists(BETTER_ANALYTICS_PLUGIN_DIR . $filename)) {
include BETTER_ANALYTICS_PLUGIN_DIR . $filename;
return class_exists($class, false) || interface_exists($class, false);
}
}
开发者ID:xalgorithm,项目名称:amcf-wp,代码行数:27,代码来源:Public.php
示例4: replace_param
function replace_param($string, $data)
{
/**
* parse query
*/
if ($string) {
while (true) {
preg_match("\$\\{(.*?)\\}\$", $string, $matches, PREG_OFFSET_CAPTURE);
if (!count($matches)) {
break;
}
$entry = $matches[0];
$type = $matches[1][0];
if (is_array($data)) {
if (array_key_exists($type, $data)) {
$string = substr_replace($string, $data[$type], $entry[1], strlen($entry[0]));
} else {
$string = substr_replace($string, "", $entry[1], strlen($entry[0]));
}
} else {
$string = substr_replace($string, $data, $entry[1], strlen($entry[0]));
}
}
}
return $string;
}
开发者ID:nibble-arts,项目名称:feedback,代码行数:26,代码来源:io.php
示例5: postflight
public function postflight(){
define('_FM_COM', 'com_profiles');
if(!defined('DS')) define('DS',DIRECTORY_SEPARATOR);
$lang = JFactory::getLanguage();
define('_MY_LANGUAGE',$lang->getTag());
define('_CLOSE_HREF','index.php');
$ABSOLUTE_URI = (getenv('HTTPS') == 'on') ? substr_replace( str_replace("http://", "https://", JURI::base() ), '', -1, 1) : substr_replace(JURI::base(), '', -1, 1) . "/";
define('_FM_ABSOLUTE_URI',$ABSOLUTE_URI);
define('_FM_HOME_URL', "index.php?option="._FM_COM."&format=raw");
define('_FM_HOME_FOLDER','components/'._FM_COM.'/filemanager');
define('_FM_HOME_DIR', JPATH_ROOT . '/administrator/components/'._FM_COM.'/filemanager');
define('_FM_LANGUAGE_DIR', _FM_HOME_DIR. DS.'languages');
define('_FM_COOKIE_EXPIRE', time()+60*60*24*60);
// Define Peer
define('_FM_PEER','joomla');
require_once _FM_HOME_DIR . DS . 'classes'.DS.'file.php';
require_once _FM_HOME_DIR . DS . 'classes'.DS.'text.php';
require_once _FM_HOME_DIR . DS .'includes'.DS.'version.php';
$infoTemplates = _FM_HOME_DIR . DS ."languages" . DS . "info";
$infoPath = $infoTemplates . DS . _MY_LANGUAGE . ".php" ;
if(!MFile::is($infoPath)){
$infoPath = $infoTemplates . DS . "en-GB.php";
}
$isWelcome = 1;
$jed = null;
$version=null;
require_once $infoPath;
} //EOF install
开发者ID:kosmosby,项目名称:medicine-prof,代码行数:35,代码来源:profiles.script.php
示例6: __autoload
function __autoload($Class)
{
$root = str_replace("/", DIRECTORY_SEPARATOR, dirname($_SERVER['SCRIPT_FILENAME']));
$ClassExtension = $Class . ".class.php";
/* * Faz uma listagem de diretórios diretórios.
*
* A seguir é feita um verificação em todos os caminhos (arquivos) para
* confirmar se existe o nome da classe chamada em algum deles.
*
*
*
* Se for achado a string da $ClassExtension no $file (caminho), será
* chamado o include_once;
*/
$root = isset($root) ? $root : '.';
// Coloque o caminho raiz!
$root = $root[strlen($root) - 1] == '\\' || $root[strlen($root) - 1] == '/' ? $root : $root . DIRECTORY_SEPARATOR;
$empytfile = null;
$car = "*";
$glob = glob($car, GLOB_MARK);
while (!empty(glob($car, GLOB_MARK))) {
if (!empty($FileClass = glob(substr_replace($car, "", -1) . $ClassExtension))) {
include_once $root . $FileClass[0];
//var_dump($root.$FileClass[0]);
$empytfile = true;
}
$car = $car . "\\*";
}
if (!$empytfile) {
trigger_error("A Classe <b><u>{$Class}</u></b> não existe.", E_USER_ERROR);
die;
}
}
开发者ID:johnnylima,项目名称:Wfood,代码行数:33,代码来源:config.inc.php
示例7: compile
/**
* @param Less_Functions $ctx
*/
public function compile($ctx)
{
$val = $this->value->compile($ctx);
if (!$this->isEvald) {
// Add the base path if the URL is relative
if (Less_Parser::$options['relativeUrls'] && $this->currentFileInfo && is_string($val->value) && Less_Environment::isPathRelative($val->value)) {
$rootpath = $this->currentFileInfo['uri_root'];
if (!$val->quote) {
$rootpath = preg_replace('/[\\(\\)\'"\\s]/', '\\$1', $rootpath);
}
$val->value = $rootpath . $val->value;
}
$val->value = Less_Environment::normalizePath($val->value);
}
// Add cache buster if enabled
if (Less_Parser::$options['urlArgs']) {
if (!preg_match('/^\\s*data:/', $val->value)) {
$delimiter = strpos($val->value, '?') === false ? '?' : '&';
$urlArgs = $delimiter . Less_Parser::$options['urlArgs'];
$hash_pos = strpos($val->value, '#');
if ($hash_pos !== false) {
$val->value = substr_replace($val->value, $urlArgs, $hash_pos, 0);
} else {
$val->value .= $urlArgs;
}
}
}
return new Less_Tree_URL($val, $this->currentFileInfo, true);
}
开发者ID:kevcom,项目名称:scheduler,代码行数:32,代码来源:Url.php
示例8: parse
public function parse($sQuery)
{
//Test the query for validity
$iBracesCounter = 0;
$iLength = strlen($sQuery);
for ($i = 0; $i < $iLength; $i++) {
$cCurrent = substr($sQuery, $i, 1);
switch ($cCurrent) {
case "(":
$iBracesCounter++;
break;
case ")":
$iBracesCounter--;
break;
}
if ($iBracesCounter < 0) {
throw new Exception("Error in BooleanParser->parse: query not well-formed");
}
}
if ($iBracesCounter != 0) {
throw new Exception("Error in BooleanParser->parse: query not well-formed");
}
while (strpos($sQuery, "(") !== false) {
$aBrace = $this->getInnermostBrace($sQuery);
$sResult = $this->booleanTextForSimpleExpression($aBrace['inner_query']);
$sQuery = substr_replace($sQuery, $sResult, $aBrace['start'], $aBrace['length']);
}
return $this->booleanForSimpleExpression($sQuery);
}
开发者ID:rapila,项目名称:cms-base,代码行数:29,代码来源:BooleanParser.php
示例9: list_folder_files
public static function list_folder_files($dir)
{
$dir_name = $dir;
if (!functions::is_empty_dir($dir)) {
$files = scandir($dir, 0);
$filename = '';
$filesize = '';
for ($ctr = 1; $ctr < sizeof($files); $ctr++) {
if ($files[$ctr] != "." && $files[$ctr] != "..") {
/*$folder_files = array(
'filename' => $files[$ctr],
'filesize' => $this->formatfilesize(filesize($dir.$files[$ctr])),
);*/
$i = $ctr . ',';
/*if(!is_dir($dir.'/'.$files[$ctr])){
$filename .= $files[$ctr].',';
}*/
if (is_dir($dir . '/' . $files[$ctr])) {
$filename .= $files[$ctr] . ' [FOLDER],';
} else {
$filename .= $files[$ctr] . ',';
}
//$filename .= $files[$ctr].',';
//$filesize .= $this->formatfilesize(filesize($dir.$files[$ctr])).',';
}
}
$exploded_i = explode(',', substr_replace($i, '', -1));
$exploded_filename = explode(',', substr_replace($filename, '', -1));
$exploded_filesize = explode(',', substr_replace($filesize, '', -1));
return $exploded_filename;
} else {
return array();
}
}
开发者ID:steamboy,项目名称:ds,代码行数:34,代码来源:functions.php
示例10: getTokens
protected function getTokens($code)
{
if ($this->lfLineEndings && false !== strpos($code, "\r")) {
$code = str_replace("\r\n", "\n", $code);
$code = strtr($code, "\r", "\n");
}
if ($this->checkUtf8 && !preg_match('//u', $code)) {
$this->setError("File encoding is not valid UTF-8", E_USER_WARNING);
}
if ($this->stripUtf8Bom && 0 === strncmp($code, "", 3)) {
// substr_replace() is for mbstring overloading resistance
$code = substr_replace($code, '', 0, 3);
$this->setError("Stripping UTF-8 Byte Order Mark", E_USER_NOTICE);
}
if ('' === $code) {
return array();
}
$code = parent::getTokens($code);
// Ensure that the first token is always a T_OPEN_TAG
if (T_INLINE_HTML === $code[0][0]) {
$a = $code[0][1];
$a = "\r" === $a[0] ? isset($a[1]) && "\n" === $a[1] ? '\\r\\n' : '\\r' : ("\n" === $a[0] ? '\\n' : '');
if ($a) {
array_unshift($code, array(T_OPEN_TAG, '<?php '), array(T_ECHO, 'echo'), array(T_ENCAPSED_AND_WHITESPACE, "\"{$a}\""), array(T_CLOSE_TAG, '?>'));
} else {
array_unshift($code, array(T_OPEN_TAG, '<?php '), array(T_CLOSE_TAG, '?>'));
}
}
// Ensure that the last valid PHP code position is tagged with a T_ENDPHP
$a = array_pop($code);
$code[] = T_CLOSE_TAG === $a[0] ? ';' : $a;
T_INLINE_HTML === $a[0] && ($code[] = array(T_OPEN_TAG, '<?php '));
$code[] = array(T_ENDPHP, '');
return $code;
}
开发者ID:nicolas-grekas,项目名称:Patchwork-sandbox,代码行数:35,代码来源:Normalizer.php
示例11: loadClass
/**
* Load the file for a class
*
* @param string $class The class that will be loaded
* @return boolean True on success
*/
public static function loadClass($class)
{
// pre-empt further searching for the named class or interface.
// do not use autoload, because this method is registered with
// spl_autoload already.
if (class_exists($class, false) || interface_exists($class, false)) {
return;
}
// if class start with a 'Nooku' it is a Nooku class.
// create the path and register it with the loader.
switch (substr($class, 0, 6)) {
case 'Picman':
$word = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', substr_replace($class, '', 0, 6)));
$parts = explode('_', $word);
if (count($parts) > 1) {
$path = KInflector::pluralize(array_shift($parts)) . DS . implode(DS, $parts);
} else {
$path = $word;
}
if (is_file(dirname(__FILE__) . DS . $path . '.php')) {
KLoader::register($class, dirname(__FILE__) . DS . $path . '.php');
}
break;
}
$classes = KLoader::register();
if (array_key_exists(strtolower($class), $classes)) {
include $classes[strtolower($class)];
return true;
}
return false;
}
开发者ID:janssit,项目名称:www.gincoprojects.be,代码行数:37,代码来源:loader.php
示例12: buildModifiedFile
private function buildModifiedFile()
{
$data = $this->getUnmodifiedFileContent();
foreach ($this->lintResult->getMessages() as $lint) {
if (!$lint->isPatchable()) {
continue;
}
$orig_offset = $this->getCharacterOffset($lint->getLine() - 1);
$orig_offset += $lint->getChar() - 1;
$dirty = $this->getDirtyCharacterOffset();
if ($dirty > $orig_offset) {
continue;
}
// Adjust the character offset by the delta *after* checking for
// dirtiness. The dirty character cursor is a cursor on the original file,
// and should be compared with the patch position in the original file.
$working_offset = $orig_offset + $this->getCharacterDelta();
$old_str = $lint->getOriginalText();
$old_len = strlen($old_str);
$new_str = $lint->getReplacementText();
$new_len = strlen($new_str);
if ($working_offset == strlen($data)) {
// Temporary hack to work around a destructive hphpi issue, see #451031.
$data .= $new_str;
} else {
$data = substr_replace($data, $new_str, $working_offset, $old_len);
}
$this->changeCharacterDelta($new_len - $old_len);
$this->setDirtyCharacterOffset($orig_offset + $old_len);
$this->applyMessages[] = $lint;
}
$this->modifiedData = $data;
}
开发者ID:ivoryxiong,项目名称:arcanist,代码行数:33,代码来源:ArcanistLintPatcher.php
示例13: __construct
public function __construct(array $params = null)
{
//All child class need to have constant UUID_CLASS_PREFIX to create uuid prefix
if (!defined(get_class($this) . '::UUID_CLASS_PREFIX')) {
throw new \Exception("Class " . get_class($this) . " has missing UUID_CLASS_PREFIX constant.");
}
//bind array values to class properties
if ($params) {
foreach ($params as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
//Add uuid if not exists for new created object
if (property_exists($this, 'uuid')) {
if (!$this->uuid) {
$uuid = Uuid::uuid4()->toString();
//Add uuid prefix (defined in UUID_CLASS_PREFIX constant) by replacing first x characters. Where x is prefix length.
$prefix_length = strlen($this::UUID_CLASS_PREFIX);
$uuid = substr_replace($uuid, $this::UUID_CLASS_PREFIX, 0, $prefix_length);
$this->uuid = $uuid;
}
}
}
开发者ID:marcyniu,项目名称:ai,代码行数:25,代码来源:Dto.php
示例14: fixPropertyPath
/**
* @param string $propertyPath
* @return string
*/
private function fixPropertyPath($propertyPath)
{
if ($propertyPath[0] != '[') {
$propertyPath = '[' . substr_replace($propertyPath, ']', strpos($propertyPath, '[') ?: strlen($propertyPath), 0);
}
return str_replace('[]', '', $propertyPath);
}
开发者ID:Lionel09,项目名称:FormExtensionsBundle,代码行数:11,代码来源:CollectionUploadListener.php
示例15: __js_wrap_quote
function __js_wrap_quote($str, $max_line_length)
{
$max_line_length -= 3;
$inQ = false;
$esc = 0;
$lineLen = 0;
$result = '';
$chunk = '';
while (strlen($str) > 0) {
if (preg_match('/^\\\\[0-7]{3}/i', $str)) {
$chunk = substr($str, 0, 3);
$str = substr_replace($str, '', 0, 3);
} elseif (preg_match('/^\\\\./i', $str)) {
$chunk = substr($str, 0, 2);
$str = substr_replace($str, '', 0, 2);
} else {
$chunk = substr($str, 0, 1);
$str = substr_replace($str, '', 0, 1);
}
if ($lineLen + strlen($chunk) >= $max_line_length) {
$result .= '"+' . "\n" . '"';
$lineLen = 1;
}
$lineLen += strlen($chunk);
$result .= $chunk;
}
return $result;
}
开发者ID:karlbright,项目名称:boilerplate-wp,代码行数:28,代码来源:enkoder.php
示例16: Gravatar
/**
* Gravatar
*
* This function returns the url of a gravatar image.
*
* @access public
* @return string
*/
function Gravatar()
{
$this->EE =& get_instance();
$rating = $this->EE->TMPL->fetch_param('rating');
$size = $this->EE->TMPL->fetch_param('size');
$default = $this->EE->TMPL->fetch_param('default');
$email = $this->EE->TMPL->fetch_param('email');
$name = $this->EE->TMPL->fetch_param('name');
if ($email == "" && $name != "") {
$results = $this->EE->db->query("SELECT email FROM exp_members WHERE screen_name = '" . $this->EE->db->escape_str($name) . "'");
$results = $results->row('email');
$email = is_array($results) ? '[email protected]' : $results;
}
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower($email)) . "?";
if ($size && $size != '') {
$grav_url .= "s=" . $size . "&";
}
if ($rating && $rating != '') {
$grav_url .= "r=" . $rating . "&";
}
if ($default && $default != '') {
$grav_url .= "d=" . $default . "&";
}
$grav_url = substr_replace($grav_url, "", -1);
$this->return_data = $grav_url;
}
开发者ID:newism,项目名称:gravatar.ee_addon,代码行数:34,代码来源:pi.gravatar.php
示例17: _addColumnFilterToCollection
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'zip') {
$value = $column->getFilter()->getValue();
if (!is_numeric($value)) {
$state = addslashes(strtoupper(substr($value, -2)));
$city = addslashes(substr_replace($value, "", -4));
$zipArr = Mage::getModel('urls/cities')->getCityZips($city, $state);
$field = $column->getFilterIndex() ? $column->getFilterIndex() : $column->getIndex();
$this->getCollection()->addAttributeToFilter($field, array('in' => $zipArr));
return $this;
}
}
// Set custom filter for in category flag
if ($column->getId() == 'in_category') {
$productIds = $this->_getSelectedProducts();
if (empty($productIds)) {
$productIds = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('entity_id', array('in' => $productIds));
} elseif (!empty($productIds)) {
$this->getCollection()->addFieldToFilter('entity_id', array('nin' => $productIds));
}
} else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
开发者ID:evinw,项目名称:project_bloom_magento,代码行数:29,代码来源:Product.php
示例18: combine
/**
* Combines multiple font-definitions into single definition
*
* @param (string) val: Rule Set
*/
public function combine( $val ) {
$storage = $this->storage( $val );
// Loop through each property check and see if they can be replaced
foreach ( $this->groupings as $props ) {
if ( $replace = $this->Combine->searchDefinitions( 'font', $storage, $props ) ) {
break;
}
}
// If replacement string found, run it on all declarations
if ( $replace ) {
$pos = 0;
while ( preg_match( $this->rfont, $val, $match, PREG_OFFSET_CAPTURE, $pos ) ) {
if ( ! isset( $storage['line-height'] ) && stripos( $match[ 0 ][ 0 ], 'line-height') === 0 ) {
$pos = $match[ 0 ][ 1 ] + strlen( $match[ 0 ][ 0 ] ) - 1;
continue;
}
$colon = strlen( $match[ 1 ][ 0 ] );
$val = substr_replace( $val, $replace, $match[ 0 ][ 1 ] + $colon, strlen( $match[ 0 ][ 0 ] ) - $colon );
$pos = $match[ 0 ][ 1 ] + strlen( $replace ) - $colon - 1;
$replace = '';
}
}
// Return converted val
return $val;
}
开发者ID:hao,项目名称:erawanchinatown,代码行数:33,代码来源:Font.php
示例19: sms_board_handle
function sms_board_handle($c_uid, $sms_datetime, $sms_sender, $sms_receiver, $board_keyword, $board_param = '')
{
global $web_title, $email_service, $email_footer, $gateway_module, $datetime_now;
$ok = false;
if ($sms_sender && $board_keyword && $board_param) {
// masked sender sets here
$masked_sender = substr_replace($sms_sender, 'xxxx', -4);
$db_query = "\n\t INSERT INTO " . _DB_PREF_ . "_featureBoard_log \n\t (in_gateway,in_sender,in_masked,in_keyword,in_msg,in_datetime) \n\t VALUES ('{$gateway_module}','{$sms_sender}','{$masked_sender}','{$board_keyword}','{$board_param}','{$datetime_now}')\n\t";
if ($cek_ok = @dba_insert_id($db_query)) {
$db_query1 = "SELECT board_forward_email FROM " . _DB_PREF_ . "_featureBoard WHERE board_keyword='{$board_keyword}'";
$db_result1 = dba_query($db_query1);
$db_row1 = dba_fetch_array($db_result1);
$email = $db_row1['board_forward_email'];
if ($email) {
// get name from c_uid's phonebook
$c_username = uid2username($c_uid);
$c_name = phonebook_number2name($sms_sender, $c_username);
$sms_sender = $c_name ? $c_name . ' <' . $sms_sender . '>' : $sms_sender;
$subject = "[SMSGW-" . $board_keyword . "] " . _('from') . " {$sms_sender}";
$body = _('Forward WebSMS') . " ({$web_title})\n\n";
$body .= _('Date and time') . ": {$sms_datetime}\n";
$body .= _('Sender') . ": {$sms_sender}\n";
$body .= _('Receiver') . ": {$sms_receiver}\n";
$body .= _('Keyword') . ": {$board_keyword}\n\n";
$body .= _('Message') . ":\n{$board_param}\n\n";
$body .= $email_footer . "\n\n";
sendmail($email_service, $email, $subject, $body);
}
$ok = true;
}
}
return $ok;
}
开发者ID:ranakhurram,项目名称:playSMS,代码行数:33,代码来源:fn.php
示例20: applyTransformationsToReachTarget
private function applyTransformationsToReachTarget($currentMolecule)
{
if ($currentMolecule == $this->molecule) {
return 0;
}
$minSteps = PHP_INT_MAX;
$transformationsNormalised = [];
foreach ($this->transformations as $source => $transformationsForSource) {
foreach ($transformationsForSource as $transformation) {
$transformationsNormalised[] = ['source' => $source, 'transformation' => $transformation];
}
}
usort($transformationsNormalised, function ($a, $b) {
return strlen($b['transformation']) - strlen($a['transformation']);
});
foreach ($transformationsNormalised as $transformationNormalised) {
$source = $transformationNormalised['source'];
$transformation = $transformationNormalised['transformation'];
for ($offset = 0; ($index = strpos($currentMolecule, $transformation, $offset)) !== false; $offset = $index + 1) {
if ($minSteps == PHP_INT_MAX || $minSteps < self::$minFoundSoFar) {
return $this->applyTransformationsToReachTarget(substr_replace($currentMolecule, $source, $index, strlen($transformation))) + 1;
}
}
}
return $minSteps;
}
开发者ID:chrisemerson,项目名称:adventOfCode,代码行数:26,代码来源:MedicineMachine.php
注:本文中的substr_replace函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论