<?php
+
+use Wikimedia\AtEase\AtEase;
+
/**
* Methods to play with strings.
*
* @return string The string with the matches replaced
*/
static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
- $replacer = new RegexlikeReplacer( $replace );
-
- return self::delimiterReplaceCallback( $startDelim, $endDelim,
- $replacer->cb(), $subject, $flags );
+ return self::delimiterReplaceCallback(
+ $startDelim, $endDelim,
+ function ( array $matches ) use ( $replace ) {
+ return strtr( $replace, [ '$0' => $matches[0], '$1' => $matches[1] ] );
+ },
+ $subject, $flags
+ );
}
/**
$text = str_replace( $placeholder, '', $text );
// Replace instances of the separator inside HTML-like tags with the placeholder
- $replacer = new DoubleReplacer( $separator, $placeholder );
- $cleaned = self::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
+ $cleaned = self::delimiterReplaceCallback(
+ '<', '>',
+ function ( array $matches ) use ( $separator, $placeholder ) {
+ return str_replace( $separator, $placeholder, $matches[0] );
+ },
+ $text
+ );
// Explode, then put the replaced separators back in
$items = explode( $separator, $cleaned );
$text = str_replace( $placeholder, '', $text );
// Replace instances of the separator inside HTML-like tags with the placeholder
- $replacer = new DoubleReplacer( $search, $placeholder );
- $cleaned = self::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
+ $cleaned = self::delimiterReplaceCallback(
+ '<', '>',
+ function ( array $matches ) use ( $search, $placeholder ) {
+ return str_replace( $search, $placeholder, $matches[0] );
+ },
+ $text
+ );
// Explode, then put the replaced separators back in
$cleaned = str_replace( $search, $replace, $cleaned );
return $text;
}
+ /**
+ * Utility function to check if the given string is a valid PCRE regex. Avoids
+ * manually calling suppressWarnings and restoreWarnings, and provides a
+ * one-line solution without the need to use @.
+ *
+ * @since 1.34
+ * @param string $string The string you want to check being a valid regex
+ * @return bool
+ */
+ public static function isValidPCRERegex( $string ) {
+ AtEase::suppressWarnings();
+ // @phan-suppress-next-line PhanParamSuspiciousOrder False positive
+ $isValid = preg_match( $string, '' );
+ AtEase::restoreWarnings();
+ return $isValid !== false;
+ }
+
/**
* Escape a string to make it suitable for inclusion in a preg_replace()
* replacement parameter.