Make replacements in a given content string

@param   string  $contents  Incoming content
@return  string
197268
private function doReplacements($contents)
	{
		// Replace variables
		if (isset($this->replacements) && count($this->replacements) > 0)
		{
			foreach ($this->replacements as $k => $v)
			{
				if (is_array($v))
				{
					foreach ($v as $replacement)
					{
						foreach ($replacement as $key => $value)
						{
							$contents = preg_replace("/%={$key}=%/", $value, $contents, 1);
						}
					}
				}
				else
				{
					// See if there are any instances of our key with special qualifiers
					if (preg_match_all("/%={$k}\+([[:alpha:]]+)=%/", $contents, $matches) && isset($matches[1]))
					{
						// Remove complete match
						unset($matches[0]);
						foreach ($matches[1] as $match)
						{
							switch ($match)
							{
								// Upper case word
								case 'uc':
									$value = strtoupper($v);
									break;
								// Upper case first character
								case 'ucf':
									$value = ucfirst($v);
									break;
								// Upper case first character and plural
								case 'ucfp':
									$value = ucfirst(Inflector::pluralize($v));
									break;
								// Plural form
								case 'p':
									$value = Inflector::pluralize($v);
									break;
							}

							$contents = str_replace("%={$k}+{$match}=%", $value, $contents);
						}
					}

					// Now do all basic replacements
					$contents = str_replace("%={$k}=%", $v, $contents);

					if ($this->doBlindReplacements)
					{
						$contents = str_replace($k, $v, $contents);
					}
				}
			}
		}

		// Now parse for nested templates
		preg_match_all('/\$\^[[:alpha:]\.]*\^\$/', $contents, $matches, PREG_SET_ORDER);

		if (isset($matches) && count($matches) > 0)
		{
			foreach ($matches as $match)
			{
				foreach ($match as $key)
				{
					// Get template contents
					$keyReal = preg_replace('/\$\^([[:alpha:]\.]*)\^\$/', '$1', $key);
					$subPath = __DIR__ . DS . 'Scaffolding' . DS . 'Templates' . DS . $this->getType() . '.' . $keyReal . '.tmpl';

					if (!is_file($subPath))
					{
						continue;
					}

					$subTmpl = file_get_contents($subPath);

					if (isset($this->replacements[$keyReal]) && is_array($this->replacements[$keyReal]))
					{
						$count    = count($this->replacements[$keyReal]);
						$repeat   = str_repeat($key, $count);
						$contents = str_replace($key, $repeat, $contents);
					}

					$contents = str_replace($key, $subTmpl, $contents);
					$contents = $this->doReplacements($contents);
				}
			}
		}

		return $contents;
	}
675949
protected function replaceElementTagsWithMarkers($content)
    {
        $tags = $this->extractTags($content);

        if ($tags) {
            $markerClass = self::$marker_class;

            $content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) {
                return '<img class="' . $markerClass . '" data-tagid="' . $idx . '" />';
            });
        }

        return array($content, $tags);
    }
1236079
public function save($contents)
	{
		// prep the contents
		$this->prep_vars($contents);
		$contents = serialize($contents);

		// update the config in the database
		$result = \DB::update($this->table)->set(array('config' => $contents, 'hash' => uniqid()))->where('identifier', '=', $this->identifier)->execute();

		// if there wasn't an update, do an insert
		if ($result === 0)
		{
			list($notused, $result) = \DB::insert($this->table)->set(array('identifier' => $this->identifier, 'config' => $contents, 'hash' => uniqid()))->execute();
		}

		return $result === 1;
	}
193942
protected function replaceElementContents($contents, PlaceholderContainer $placeholderContainer)
    {
        $htmlTags = implode('|', $this->htmlPlaceholderTags);

        $pattern = '/
            (
                <(' . $htmlTags . ')                    # Match html start tag and capture
                    (?:
                        [^"\'>]*|"[^"]*"|\'[^\']*\'
                    )*                                  # Match all attributes
                >                                       # Match end of tag
            )
            (
                (?:                                     # Negotiate this part
                    (?!<\/\2>)                          # Negative look ahead for the end tag
                    .                                   # Match everything if not the end tag 
                )*+                                     # Possessive quantifier which will prevent backtracking
            )
            (<\/\2>)                                    # Match end tag by back referencing the start tag
            /xis';

        return preg_replace_callback($pattern, function ($match) use ($placeholderContainer) {
            return $match[1].$placeholderContainer->createPlaceholder($match[3]).$match[4];
        }, $contents);
    }
1319376
public function replaceIdxContentContents(array $contents)
    {
        $parentUids = array();
        foreach ($contents as $content) {
            // avoid loop if content is already treated
            if (null === $content || true === $content->isElementContent()) {
                continue;
            } elseif (true === array_key_exists($content->getUid(), $parentUids)) {
                break;
            } elseif (false === array_key_exists($content->getUid(), $parentUids)) {
                $parentUids[$content->getUid()] = array($content->getUid());
            }

            $parentUids[$content->getUid()] = array_merge($parentUids[$content->getUid()], $this->getAClassContentUids($content->getSubcontent()->toArray()));
        }

        return $this->replaceIdxContentContentsByUids($parentUids);
    }
806561
public function addContents($contents)
    {
        if (current($contents) instanceof Content) {
            foreach ($contents as $content) {
                $this->addContent($content);
            }
        } else {
            foreach ($contents as $key => $value) {
                $this->addContent($key, $value);
            }
        }
    }
334010
protected function _replace($content)
    {
        $content = trim($content, "\r\n ");
        if (!$this->blocks) {
            return $content;
        }

        return strtr($content, $this->blocks);
    }
1326124
protected function fillContent($content)
    {
        preg_match_all('/\[\[(.*?)\]\]/', $content, $matches);
        if (!isset($matches[0]) or ! isset($matches[1])) {
            return $content;
        }
        $notifications = \Antares\Foundation\Notification::getInstance()->all();

        foreach ( (array) $matches[1] as $index => $match) {
            if (!str_contains($match, '::')) {
                continue;
            }
            list($component, $var) = explode('::', trim($match));
            $name = $this->findExtensionName($component);

            $variables = isset($notifications[$name]['variables']) ? $notifications[$name]['variables'] : [];
            event('notifications:notification.variables', [&$variables]);
            $value     = $this->resolveValue($var, $variables);

            if (is_array($value)) {
                $value = $this->getDefaultNotificationForList($value)->render();
            }

            $content = str_replace($matches[0][$index], $value, $content);
        }
        return $content;
    }
1248738
protected function preProcessPostContent( $content ) {
		$content = apply_filters( 'the_content', $content );
		$content = str_ireplace( [ '<b></b>', '<i></i>', '<strong></strong>', '<em></em>' ], '', $content );
		$content = $this->fixAnnoyingCharacters( $content );
		$content = $this->tidy( $content );

		return $content;
	}
1119973
protected function preProcessPostContent( $content ) {
		$content = apply_filters( 'the_export_content', $content );
		$content = str_ireplace( [ '<b></b>', '<i></i>', '<strong></strong>', '<em></em>' ], '', $content );
		$content = $this->fixAnnoyingCharacters( $content ); // is this used?
		$content = $this->fixInternalLinks( $content );
		$content = $this->switchLaTexFormat( $content );
		if ( ! empty( $_GET['optimize-for-print'] ) ) {
			$content = $this->fixImages( $content );
		}
		$content = $this->tidy( $content );

		return $content;
	}
344618
function modifyContent(&$content) {
    	//Remove comments
		$content = preg_replace('#\/\*(?!\*\/)(.*?)\*\/#si', '', $content);
		$content = str_replace('<!--', '', $content);
		$content = str_replace('-->', '', $content);
		$content = trim($content);

		if (!isset($this->url)) return $content;
		$this->regex = array();
		$this->replace = array();

		$pathinfo = parse_url($this->url);

		$sorceurl = $pathinfo['scheme'] . '://' . $pathinfo['host'] . '/';

		$sorcepath = explode('/', $pathinfo['path']);
		array_shift($sorcepath);
		array_pop($sorcepath);

		$sorcepathoriginal = $sorcepath;

		while(count($sorcepath)) {
			$temp = $sorcepathoriginal;
			$path = '';
			foreach($sorcepath as $values) {
				$path .= '\.\.\/';
				array_pop($temp);
			}

			$turl = $sorceurl;
			if (count($temp)) {
				$turl .= implode('/', $temp) . '/';
			}
			$this->regex[] = '#' . $path . '#iSs';
			$this->replace[] = $turl;
			array_pop($sorcepath);
		}

		$this->thisUrl = $sorceurl . implode('/', $sorcepathoriginal) . '/';

		$this->regex[] = '#\.\/#is';
		$this->replace[] = $sorceurl . implode('/', $sorcepathoriginal) . '/';

		$this->regex[] = '#url\(([^"\'\)]*)\)#is';
		$this->replace[] = 'url("$1")';

		$this->regex[] = '#url\(["\']/([^"\']*)["\']\)#Sis';
		$this->replace[] = 'url("' . $sorceurl . '$1")';

		$this->regex[] = '#url\(["\'](?!\w{0,10}://)([^"\']*)["\']\)#Sis';
		$this->replace[] = 'url("' . $sorceurl . implode('/', $sorcepathoriginal) . '/$1")';

		$regexall = $this->regex;
		$replaceall = $this->replace;

		$content = preg_replace($regexall, $replaceall, $content);

		if (preg_match_all('#@import.*?[\'"]([^\'"]*)[\'"].*?;#Sis', $content, $imports)) {
			foreach ($imports[1] as $key => $import) {
				$cssparser = new Css($this->prefix);
				$cssparser->ParseUrl($import);
				$temp = $cssparser->GetCSS();

				$content = str_replace($imports[0][$key], '', $content );

				$content = $temp . $content;
			}
		}
		return $content;
	}
195662
protected function _replace($matches)
    {
        $file = $this->_currentFile;
        if ($matches[1] === '"') {
            // Same directory include
            $file = $this->_findFile($matches[2], dirname($file) . DIRECTORY_SEPARATOR);
        } else {
            // scan all paths
            $file = $this->_findFile($matches[2]);
        }

        // prevent double inclusion
        if (isset($this->_loaded[$file])) {
            return "";
        }
        $this->_loaded[$file] = true;

        $content = file_get_contents($file);
        if ($return = $this->input($file, $content)) {
            return $return . "\n";
        }
        return '';
    }
694150
private String replaceOptionals(String contents) {
        if (!replaceOptionals) {
            return contents;
        }
        try {
            final Pattern pattern = Pattern.compile("@\\{(.[^}]*)\\}");
            final Collection<String> columns = getColumnNames();
            columns.add("row.rowNumber");
            final BufferedReader reader = new BufferedReader(new StringReader(
                    contents));
            String line = null;
            final StringBuffer newLine = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                final Matcher matcher = pattern.matcher(line);
                int optCols = 0;
                while (matcher.find()) {
                    final String c = matcher.group(1);
                    if (!columns.contains(c)) {
                        newLine.append("@if{").append(matcher.group(1)).append(
                                " != null}");
                        optCols++;
                    }
                }
                newLine.append(line);
                newLine.append(StringUtils.repeat("@end{}", optCols));
                newLine.append("\n");
            }
            //            logger.info("newLine: " + newLine);
            return newLine.toString();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
959065
protected function replace($string)
    {
        foreach ($this->patterns as $key => $value) {
            $string = str_replace($key, $value, $string);
        }

        return $string;
    }
182396
public function restorePlaceholders($contents)
    {
        foreach ($this->all() as $placeholder => $original) {
            $contents = str_replace($placeholder, $original, $contents);
        }

        return $contents;
    }
138089
public static function replaceTpl($content, array $placeholders = null, Template $template)
    {
        $template = clone $template;
        $template->removeAllPlaceholders();

        return $template->replace($content, $placeholders);
    }
734019
protected function _replace($matches)
    {
        $required = empty($matches[2]) ? $matches[4] : $matches[2];
        $filename = $this->scanner()->find($required);
        if (!$filename) {
            throw new RuntimeException(sprintf('Could not find dependency "%s"', $required));
        }
        if (empty($this->_loaded[$filename])) {
            return $this->input($filename, file_get_contents($filename));
        }
        return '';
    }