/** * Sets a regular expression tested against the current value of the object * or when the value is set. See verifyValue. * @param string $match */ public function setRegexpMatch($match) { $test = ''; if (!empty($this->value)) { $test = $this->value; } if (preg_match($match, $test) === false) { throw new \Exception(t('Regular expression error: %s', preg_error_msg(preg_last_error()))); } $this->regexp_match = $match; }
function smarty_outputfilter_shortcodes($output, Smarty_Internal_Template $template) { $shortcodes = \Xoops\Core\Text\Sanitizer::getInstance()->getShortCodes(); $shortcodes->addShortcode('nosc42', function ($attributes, $content, $tagName) { return $content; }); // break out the body content $bodyPattern = '/<body[^>]*>(.*?)<\\/body>/is'; // breaks out form elements $scPattern = '/((<textarea[\\S\\s]*\\/textarea>)|(<input[\\S\\s]*>)|(<select[\\S\\s]*\\/select>)|(<script[\\S\\s]*\\/script>)|(<style[\\S\\s]*\\/style>))/U'; $text = preg_replace_callback($bodyPattern, function ($matches) use($scPattern, $shortcodes) { $element = preg_replace_callback($scPattern, function ($innerMatches) { return '[nosc42]' . $innerMatches[0] . '[/nosc42]'; }, $matches[1]); if ($element === null) { trigger_error('preg_last_error=' . preg_last_error(), E_USER_WARNING); return $matches[1]; } return $element; }, $output); if ($text === null) { trigger_error('preg_last_error=' . preg_last_error(), E_USER_WARNING); return $output; } $text = $shortcodes->process($text); return $text; }
private function _preg_error() { switch (preg_last_error()) { case PREG_INTERNAL_ERROR: echo 'PREG_INTERNAL_ERROR'; break; case PREG_BACKTRACK_LIMIT_ERROR: echo 'PREG_BACKTRACK_LIMIT_ERROR'; break; case PREG_RECURSION_LIMIT_ERROR: echo 'PREG_RECURSION_LIMIT_ERROR'; break; case PREG_BAD_UTF8_ERROR: echo 'PREG_BAD_UTF8_ERROR'; break; case PREG_BAD_UTF8_OFFSET_ERROR: echo 'PREG_BAD_UTF8_OFFSET_ERROR'; break; default: //die("Unknown preg error."); return; } echo "<hr><pre>"; debug_print_backtrace(); die; }
/** * @param TexyBlockParser * @param string text * @param array * @param TexyHtml * @return vois */ public function process($parser, $content, $el) { $tx = $this->texy; if ($parser->isIndented()) { $parts = preg_split('#(\n(?! )|\n{2,})#', $content, -1, PREG_SPLIT_NO_EMPTY); } else { $parts = preg_split('#(\n{2,})#', $content, -1, PREG_SPLIT_NO_EMPTY); } foreach ($parts as $s) { $s = trim($s); if ($s === '') continue; // try to find modifier $mx = $mod = NULL; if (preg_match('#'.TEXY_MODIFIER_H.'(?=\n|\z)#sUm', $s, $mx, PREG_OFFSET_CAPTURE)) { list($mMod) = $mx[1]; $s = trim(substr_replace($s, '', $mx[0][1], strlen($mx[0][0]))); if ($s === '') continue; $mod = new TexyModifier; $mod->setProperties($mMod); } elseif (TEXY_CHECK_PCRE && preg_last_error()) { throw new TexyPcreException; } $res = $tx->invokeAroundHandlers('paragraph', $parser, array($s, $mod)); if ($res) $el->insert(NULL, $res); } }
static function trim($value, $max_length, $is_html = false) { if (UTF8::len($value) > $max_length) { $value = UTF8::sub($value, 0, $max_length); // TODO: replace this with cleanstring of ctools $regex = '(.*)\\b.+'; $matches = array(); if (function_exists('mb_ereg')) { mb_regex_encoding('UTF-8'); $found = mb_ereg($regex, $value, $matches); } else { $found = preg_match("/{$regex}/us", $value, $matches); } if ($found) { $value = $matches[1]; } if ($is_html) { // Remove scraps of HTML entities from the end of a strings $regex = '/(?:<(?!.+>)|&(?!.+;)).*$/s'; $value2 = preg_replace($regex . 'u', '', $value); if (preg_last_error() == 4) { $value = preg_replace($regex, '', $value); } else { $value = $value2; } } $value = rtrim($value); $value .= '...'; } if ($is_html) { $value = self::_filter_htmlcorrector($value); } return $value; }
/** * Tokenizes string. * @param string * @return array */ public function tokenize($input) { preg_match_all($this->re, $input, $tokens, PREG_SET_ORDER); if (preg_last_error()) { throw new RegexpException(NULL, preg_last_error()); } $len = 0; $count = count($this->types); foreach ($tokens as &$match) { $type = NULL; for ($i = 1; $i <= $count; $i++) { if (!isset($match[$i])) { break; } elseif ($match[$i] != NULL) { $type = $this->types[$i - 1]; break; } } $match = array(self::VALUE => $match[0], self::OFFSET => $len, self::TYPE => $type); $len += strlen($match[self::VALUE]); } if ($len !== strlen($input)) { list($line, $col) = $this->getCoordinates($input, $len); $token = str_replace("\n", '\\n', substr($input, $len, 10)); throw new CompileException("Unexpected '{$token}' on line {$line}, column {$col}."); } return $tokens; }
private static function _checkError() { $code = preg_last_error(); if ($code != PREG_NO_ERROR) { self::_throwError($code); } }
/** * Construct the exception. Note: The message is NOT binary safe. * * @param string $message Description where regex error occurred. * @param string $regex Pattern which caused error. * @param Exception $previous [optional] The previous exception used for the exception chaining. Since 5.3.0 */ public function __construct($message, $regex, Exception $previous = null) { $lastError = preg_last_error(); $lastErrorText = isset($this->pregErrors[$lastError]) ? $this->pregErrors[$lastError] : "preg error #{$lastError}"; $message .= ". Pattern {$regex} cannot be used" . ($lastError === PREG_NO_ERROR ? '.' : ": {$lastErrorText}."); parent::__construct($message, 0, $previous); }
function tokenize($source) { $result = new TokenStream(); $pos = 0; $matches = array(); preg_match_all($this->pattern, $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) { throw new TemplateSyntaxError('Template too large, PCRE backtrack limit reached'); } foreach ($matches as $match) { if (!isset($match["match"])) { throw new TemplateSyntaxError('Template error'); } $tagpos = $match["match"][1]; if ($tagpos > 0) { $text = substr($source, $pos, $tagpos - $pos); $result->feed('text', $text, $pos); } if (isset($match["block"]) && $match["block"][1] != -1) { $result->feed('block', trim($match["block"][0]), $tagpos); } elseif (isset($match["variable"]) && $match["variable"][1] != -1) { $result->feed('variable', trim($match["variable"][0]), $tagpos); } elseif (iset($match["comment"]) && $match["comment"][1] != -1) { $result->feed('comment', trim($match["comment"][0]), $tagpos); } $pos = $tagpos + strlen($match["match"][0]); } if ($pos < strlen($source)) { $result->feed('text', substr($source, $pos), $pos); } $result->close(); return $result; }
private function _preg_error() { switch (preg_last_error()) { case PREG_INTERNAL_ERROR: echo 'PREG_INTERNAL_ERROR'; break; case PREG_BACKTRACK_LIMIT_ERROR: echo 'PREG_BACKTRACK_LIMIT_ERROR'; break; case PREG_RECURSION_LIMIT_ERROR: echo 'PREG_RECURSION_LIMIT_ERROR'; break; case PREG_BAD_UTF8_ERROR: echo 'PREG_BAD_UTF8_ERROR'; break; // This is only valid for php > 5.3, not certain how to code around it for unit tests // case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break; // This is only valid for php > 5.3, not certain how to code around it for unit tests // case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break; default: //die("Unknown preg error."); return; } echo "<hr><pre>"; debug_print_backtrace(); die; }
/** * @brief Performs a search for the given pattern past the given index. * @param $search the pattern to search for * @param $index the minimum string index (offset) of a result * @param $matches a reference to the return location of the match groups * @return the index or false if no match is found. */ public function match($search, $index, &$matches) { $r = false; // return value if (isset($this->cache[$search])) { $a = $this->cache[$search]; if ($a === false) { return false; } // no more results $r = $a[0]; $matches = $a[1]; assert($matches !== null); if ($r >= $index) { // cache is good! return $r; } } // cache not set, or out of date, we have to perform the match if (!($ret = preg_match($search, $this->string, $matches_, PREG_OFFSET_CAPTURE, $index))) { if ($ret === false && LUMINOUS_DEBUG) { throw new Exception('preg_match returned false for pattern: "' . $search . '", with code: ' . LuminousUtils::pcre_error_decode(preg_last_error())); } $this->cache[$search] = false; return false; } $r = $matches_[0][1]; // strip the offsets from the match_groups foreach ($matches_ as $i => &$v) { $v = $v[0]; } $this->cache[$search] = array($r, $matches_); $matches = $matches_; return $r; }
function preg_error_message($code = null) { if ($code === null) { $code = preg_last_error(); } $code = (int) $code; switch ($code) { case PREG_NO_ERROR: $result = 'PCRE: No error, probably invalid regular expression.'; break; case PREG_INTERNAL_ERROR: $result = 'PCRE: Internal error.'; break; case PREG_BACKTRACK_LIMIT_ERROR: $result = 'PCRE: Backtrack limit has been exhausted.'; break; case PREG_RECURSION_LIMIT_ERROR: $result = 'PCRE: Recursion limit has been exhausted.'; break; case PREG_BAD_UTF8_ERROR: $result = 'PCRE: Malformed UTF-8 data.'; break; default: if (is_php('5.3') && $code == PREG_BAD_UTF8_OFFSET_ERROR) { $result = 'PCRE: Did not end at a valid UTF-8 codepoint.'; } elseif (is_php('7') && $code == PREG_JIT_STACKLIMIT_ERROR) { $result = 'PCRE: Failed because of limited JIT stack space.'; } else { $result = 'PCRE: Error ' . $code . '.'; } break; } return $result; }
public function parse($string) { $parsed = array(); switch ($this->function) { case self::PREG_MATCH: if (@preg_match($this->pattern, $string, $parsed, $this->flags) === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; case self::PREG_MATCH_ALL: if (@preg_match_all($this->pattern, $string, $parsed, $this->flags) === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; case self::PREG_SPLIT: $parsed = @preg_split($this->pattern, $string, null, $this->flags); if ($parsed === false) { X_Debug::w("Invalid pattern (" . preg_last_error() . "): {$this->pattern}"); $parsed = array(); } break; default: X_Debug::e("Invalid function code provided: {$this->function}"); } return $parsed; }
/** * test that the given value complies with the regular expression * * @param string $value * @return bool * @throws \RuntimeException in case the used regular expresion is invalid */ public function matches(string $value) : bool { $check = @preg_match($this->pattern, $value); if (false === $check) { throw new \RuntimeException(sprintf('Failure while matching "%s", reason: %s.', $this->pattern, $this->messageFor(preg_last_error()))); } return 1 != $check ? false : true; }
private function removeJsFromTemplate($template, $tagName) { $template = preg_replace('/<script .*type="text\\/javascript"[^>]*>.*<\\/script>/is', "", $template); if (!$template) { throw new \RuntimeException("Riot tag template compilation failed for tag: " . $tagName . " with error code: " . preg_last_error()); } return $template; }
public function testExceptionMessageEndsWithErrorMessageExplanationIfErrorOccured() { if (preg_last_error() !== PREG_NO_ERROR) { $this->fail('Test runtime error - preg_last_error is not clear, it contains error code of ' . preg_last_error()); } $exception = new RegexException('', 'REGEX'); $this->assertStringEndsWith('Pattern REGEX cannot be used.', $exception->getMessage()); }
/** * Single block pre-processing. * @param TexyBlockParser * @param string * @return void */ public function beforeBlockParse($parser, &$text) { // autoclose exclusive blocks $text = preg_replace('#^(/--++ *+(?!div|texysource).*)$((?:\\n.*+)*?)(?:\\n\\\\--.*$|(?=(\\n/--.*$)))#mi', "\$1\$2\n\\--", $text); if (preg_last_error()) { throw new TexyPcreException(); } }
/** * Construct a new BasicPath. * * @param $pattern * An regular expression pattern, without start and end markers. */ public function __construct($pattern) { $result = @preg_match('#' . strtr($pattern, '#', '\\#') . '#', 'foo'); if ($pattern != '*' && ($result === FALSE || preg_last_error() != PREG_NO_ERROR)) { throw new \InvalidArgumentException('BasicPath pattern is not a valid regular expression.'); } $this->pattern = $pattern; }
/** * Text pre-processing. * @param Texy * @param string * @return void */ public function beforeParse($texy, &$text) { if (!empty($texy->allowed['image/definition'])) { // [*image*]: urls .(title)[class]{style} $text = preg_replace_callback('#^\\[\\*([^\\n]{1,100})\\*\\]:\\ +(.{1,1000})\\ *' . TEXY_MODIFIER . '?\\s*()$#mUu', array($this, 'patternReferenceDef'), $text); if (preg_last_error()) { throw new TexyPcreException(); } } }
public static function assertMatchResult($result, string $exceptionClass, string $message) { if (false !== $result) { return; // No error. } $errorCode = preg_last_error(); $errorMessage = self::buildPregErrorMessage($errorCode); throw new $exceptionClass("{$message}: {$errorMessage}", $errorCode); }
/** * Text pre-processing. * @param Texy * @param string * @return void */ public function beforeParse($texy, &$text) { self::$livelock = array(); // [la trine]: http://www.latrine.cz/ text odkazu .(title)[class]{style} if (!empty($texy->allowed['link/definition'])) { $text = preg_replace_callback('#^\\[([^\\[\\]\\#\\?\\*\\n]{1,100})\\]: ++(\\S{1,1000})(\\ .{1,1000})?' . TEXY_MODIFIER . '?\\s*()$#mUu', array($this, 'patternReferenceDef'), $text); if (preg_last_error()) { throw new TexyPcreException(); } } }
/** * Set and validate the regular expression. * * @param string $regexp * @return void * @throws LogicException RegExp failed the validation test. */ protected function setRegexp($regexp) { $this->regexp = (string) $regexp; // suppress any regexp warnings and rely on the return value set_error_handler(function () { }); if (false === preg_match($this->regexp, uniqid())) { throw new \LogicException('Invalid regular expression', preg_last_error()); } restore_error_handler(); }
public function __construct(array $options = []) { parent::__construct($options); $options = $this->getOptions(); if (!isset($options['pattern'])) { throw new \Gajus\Vlad\Exception\InvalidArgumentException('"pattern" property is required.'); } if (@preg_match($options['pattern'], 'test') === false) { throw new \Gajus\Vlad\Exception\InvalidArgumentException('Pattern "' . $options['pattern'] . '" failed (' . array_flip(get_defined_constants(true)['pcre'])[preg_last_error()] . ').'); } }
function linking($source, $use_icon) { $source = str_replace('youtu.be/', 'youtube.com/watch?v=', $source); $render = preg_replace('@https?:\\/\\/([-\\w\\.]+[-\\w])+(:\\d+)?\\/[\\w\\/_~\\%\\+\\.-]+\\.(png|gif|jpg|jpeg)((\\?\\S+)?[^\\.\\s])?@i', ' <a href="$0" class="fancybox"><img src="media_icon/photolink.gif"/></a> ', $source); if (preg_last_error()) { $render = $source; } $render = preg_replace('@https?:\\/\\/(www\\.)?youtube.com/watch\\?v=[\\w_-]*@i', ' <a href="$0" class="fancybox-video"><img src="media_icon/youtube.gif"/></a> ', $render); $render = preg_replace('@https?:\\/\\/(www\\.)?vimeo.com/[0-9]*@i', ' <a href="$0" class="fancybox-vimeo"><img src="media_icon/vimeo.gif"/></a> ', $render); $render = preg_replace('@([^=][^"])(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.\\%\\+#-]*(\\?\\S+)?[^\\.\\s])?)?)@', '$1<a href="$2" target="_blank">$2</a>', $render); return preg_replace('@^(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.~\\%\\+#-=]*(\\?\\S+)?[^\\.\\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $render); }
/** * @param $regularExpression * @param $propertyPath * @return void */ public static function validRegularExpression($regularExpression, $propertyPath) { $pregMatchErrored = false; set_error_handler(function () use(&$pregMatchErrored) { $pregMatchErrored = true; }); preg_match($regularExpression, 'some test string'); restore_error_handler(); if ($pregMatchErrored || preg_last_error()) { throw static::createException($regularExpression, sprintf('The pattern "%s" is not a valid regular expression', self::stringify($regularExpression)), static::INVALID_REGULAR_EXPRESSION, $propertyPath); } }
function _l10n_preg_replace($needle, $new, $buffer, $limit = -1) { $tmp = preg_replace($needle, $new, $buffer, $limit); if (NULL !== $tmp) { $buffer = $tmp; $err = preg_last_error(); // put email-sending or a log-message here } else { _l10n_preg_replace_err(); } unset($tmp); return $buffer; }
function exit_on_bad_node_name($name) { //Check that the name includes only Perl word characters, i.e., alphanumeric characters and '_'s. //This is more strict than we need to be but safer than letting the user use every character other than '/' //and still flexible enough that the user can devise a wide variety of descriptive node names. $name_has_bad_char = preg_match('/[\\W]+/', $name); //Check that preg_match has not failed. if ($name_has_bad_char === FALSE) { switch (preg_last_error()) { case PREG_NO_ERROR: $error_message = "no error"; break; case PREG_INTERNAL_ERROR: $error_message = "internal error"; break; case PREG_BACKTRACK_LIMIT_ERROR: $error_message = "too many backtracks"; break; case PREG_RECURSION_LIMIT_ERROR: $error_message = "too many recursions"; break; case PREG_BAD_UTF8_ERROR: $error_message = "bad UTF8 character"; break; case PREG_BAD_UTF8_OFFSET_ERROR: $error_message = "bad UTF8 offset"; break; default: $error_message = "unknown error"; } //end of switch over different error codes for regular expression matcher exit_with_error_json("An error occurred during checking of the filename for bad characters: " . $error_message); } //end of if preg_match failed if ($name_has_bad_char) { exit_with_error_json("The name \"" . $name . "\" contains a character that was not a letter, number, or underscore."); } //Check that the name is not too long. if (strlen($name) > MAX_NAME_LENGTH) { exit_with_error_json("The name \"" . $name . "\" is longer than " . MAX_NAME_LENGTH . " bytes."); } //Check that the name is not the empty string. if (strlen($name) < 1) { exit_with_error_json("The name is an empty string."); } //Check that creating the directory will leave a safe amount of free disk space. //Since Linux keeps various temporary files around until it needs to clear them, this may not reflect all the memory potentially available. //if( disk_free_space('.') - strlen($name) < MEMORY_SAFETY_MARGIN) { // exit_with_error_json("Creating a file or directory named \"".$name."\" would leave fewer than ".MEMORY_SAFETY_MARGIN." bytes of disk space. ".disk_free_space('.')." bytes currently free."); //} }
/** * Process the PatternMatch. * * @return boolean|null A single boolean with a value of true if the sub-expression matches the pattern and false if it does not. If the sub-expression is NULL, the the operator results in NULL. * @throws \qtism\runtime\expressions\operators\OperatorProcessingException */ public function process() { $operands = $this->getOperands(); if ($operands->containsNull() === true) { return null; } if ($operands->exclusivelySingle() === false) { $msg = "The PatternMatch operator only accepts operands with a single cardinality."; throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_CARDINALITY); } if ($operands->exclusivelyString() === false) { $msg = "The PatternMatch operator only accepts operands with a string baseType."; throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_BASETYPE); } // XML schema always implicitly anchors the entire regular expression // because there is no carret (^) nor dollar ($) signs. // see http://www.regular-expressions.info/xml.html $rawPattern = $this->getExpression()->getPattern(); $pattern = OperatorUtils::escapeSymbols($rawPattern, array('$', '^')); $pattern = OperatorUtils::pregAddDelimiter('^' . $pattern . '$'); // XSD regexp always case-sensitive (nothing to do), dot matches white-spaces (use PCRE_DOTALL). $pattern .= 's'; $result = @preg_match($pattern, $operands[0]->getValue()); if ($result === 1) { return new Boolean(true); } elseif ($result === 0) { return new Boolean(false); } else { $error = preg_last_error(); $errorType = 'PCRE Engine compilation error'; switch ($error) { case PREG_INTERNAL_ERROR: $errorType = "PCRE Engine internal error"; break; case PREG_BACKTRACK_LIMIT_ERROR: $errorType = "PCRE Engine backtrack limit exceeded"; break; case PREG_RECURSION_LIMIT_ERROR: $errorType = "PCRE Engine recursion limit exceeded"; break; case PREG_BAD_UTF8_ERROR: $errorType = "PCRE Engine malformed UTF-8"; break; case PREG_BAD_UTF8_OFFSET_ERROR: $errorType = "PCRE Engine UTF-8 offset error"; break; } $msg = "An internal error occured while processing the regular expression '{$rawPattern}': {$errorType}."; throw new OperatorProcessingException($msg, $this, OperatorProcessingException::RUNTIME_ERROR); } }
private function matchOffset($buffer, $offset, $pattern, $index) { $return = NULL; $found = preg_match($pattern, $buffer, $match, PREG_OFFSET_CAPTURE, $offset); if (false === $found) { $error = preg_last_error(); throw new UnexpectedValueException(sprintf('Regular expression ("%s") failed (Error-Code: %d).', $pattern, $error)); } $found && isset($match[$index][1]) && $match[$index][1] === $offset && ($return = $match[$index][0]); return $return; }
/** * Sets the pattern option * * @param string $pattern * @throws Exception\InvalidArgumentException if there is a fatal error in pattern matching * @return Regex Provides a fluent interface */ public function setPattern($pattern) { $this->pattern = (string) $pattern; $status = @preg_match($this->pattern, 'Test'); $error = preg_last_error(); if (false === $status) { throw new Exception\InvalidArgumentException("Internal error parsing the pattern '{$this->pattern}'", 0, $error); } return $this; }