3 * Methods to play with strings.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * A collection of static methods to play with strings.
28 * Test whether a string is valid UTF-8.
30 * The function check for invalid byte sequences, overlong encoding but
31 * not for different normalisations.
33 * @note In MediaWiki 1.21, this function did not provide proper UTF-8 validation.
34 * In particular, the pure PHP code path did not in fact check for overlong forms.
35 * Beware of this when backporting code to that version of MediaWiki.
38 * @param string $value String to check
39 * @return bool Whether the given $value is a valid UTF-8 encoded string
41 static function isUtf8( $value ) {
42 $value = (string)$value;
44 // Before PHP 5.4, values above U+10FFFF are incorrectly allowed, so we have to
45 // check for them separately.
47 if ( $newPHP === null ) {
48 $newPHP = !mb_check_encoding( "\xf4\x90\x80\x80", 'UTF-8' );
51 return mb_check_encoding( $value, 'UTF-8' ) &&
52 ( $newPHP ||
preg_match( "/\xf4[\x90-\xbf]|[\xf5-\xff]/S", $value ) === 0 );
56 * Perform an operation equivalent to `preg_replace()`
60 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
62 * ..except that it's worst-case O(N) instead of O(N^2). Compared to delimiterReplace(), this
63 * implementation is fast but memory-hungry and inflexible. The memory requirements are such
64 * that I don't recommend using it on anything but guaranteed small chunks of text.
66 * @param string $startDelim
67 * @param string $endDelim
68 * @param string $replace
69 * @param string $subject
72 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
73 $segments = explode( $startDelim, $subject );
74 $output = array_shift( $segments );
75 foreach ( $segments as $s ) {
76 $endDelimPos = strpos( $s, $endDelim );
77 if ( $endDelimPos === false ) {
78 $output .= $startDelim . $s;
80 $output .= $replace . substr( $s, $endDelimPos +
strlen( $endDelim ) );
88 * Perform an operation equivalent to `preg_replace_callback()`
92 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject );
94 * If the start delimiter ends with an initial substring of the end delimiter,
95 * e.g. in the case of C-style comments, the behavior differs from the model
96 * regex. In this implementation, the end must share no characters with the
97 * start, so e.g. `/*\/` is not considered to be both the start and end of a
98 * comment. `/*\/xy/*\/` is considered to be a single comment with contents `/xy/`.
100 * The implementation of delimiterReplaceCallback() is slower than hungryDelimiterReplace()
101 * but uses far less memory. The delimiters are literal strings, not regular expressions.
103 * @param string $startDelim Start delimiter
104 * @param string $endDelim End delimiter
105 * @param callable $callback Function to call on each match
106 * @param string $subject
107 * @param string $flags Regular expression flags
108 * @throws InvalidArgumentException
111 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback,
112 $subject, $flags = ''
118 $encStart = preg_quote( $startDelim, '!' );
119 $encEnd = preg_quote( $endDelim, '!' );
120 $strcmp = strpos( $flags, 'i' ) === false ?
'strcmp' : 'strcasecmp';
121 $endLength = strlen( $endDelim );
124 while ( $inputPos < strlen( $subject ) &&
125 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE
, $inputPos )
127 $tokenOffset = $m[0][1];
128 if ( $m[1][0] != '' ) {
130 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0
132 # An end match is present at the same location
134 $tokenLength = $endLength;
136 $tokenType = 'start';
137 $tokenLength = strlen( $m[0][0] );
139 } elseif ( $m[2][0] != '' ) {
141 $tokenLength = strlen( $m[0][0] );
143 throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__
);
146 if ( $tokenType == 'start' ) {
147 # Only move the start position if we haven't already found a start
148 # This means that START START END matches outer pair
149 if ( !$foundStart ) {
151 $inputPos = $tokenOffset +
$tokenLength;
152 # Write out the non-matching section
153 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
154 $outputPos = $tokenOffset;
155 $contentPos = $inputPos;
158 # Move the input position past the *first character* of START,
159 # to protect against missing END when it overlaps with START
160 $inputPos = $tokenOffset +
1;
162 } elseif ( $tokenType == 'end' ) {
165 $output .= call_user_func( $callback, [
166 substr( $subject, $outputPos, $tokenOffset +
$tokenLength - $outputPos ),
167 substr( $subject, $contentPos, $tokenOffset - $contentPos )
171 # Non-matching end, write it out
172 $output .= substr( $subject, $inputPos, $tokenOffset +
$tokenLength - $outputPos );
174 $inputPos = $outputPos = $tokenOffset +
$tokenLength;
176 throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__
);
179 if ( $outputPos < strlen( $subject ) ) {
180 $output .= substr( $subject, $outputPos );
187 * Perform an operation equivalent to `preg_replace()` with flags.
191 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject );
193 * @param string $startDelim Start delimiter regular expression
194 * @param string $endDelim End delimiter regular expression
195 * @param string $replace Replacement string. May contain $1, which will be
196 * replaced by the text between the delimiters
197 * @param string $subject String to search
198 * @param string $flags Regular expression flags
199 * @return string The string with the matches replaced
201 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
202 $replacer = new RegexlikeReplacer( $replace );
204 return self
::delimiterReplaceCallback( $startDelim, $endDelim,
205 $replacer->cb(), $subject, $flags );
209 * More or less "markup-safe" explode()
210 * Ignores any instances of the separator inside `<...>`
211 * @param string $separator
212 * @param string $text
215 static function explodeMarkup( $separator, $text ) {
216 $placeholder = "\x00";
218 // Remove placeholder instances
219 $text = str_replace( $placeholder, '', $text );
221 // Replace instances of the separator inside HTML-like tags with the placeholder
222 $replacer = new DoubleReplacer( $separator, $placeholder );
223 $cleaned = StringUtils
::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
225 // Explode, then put the replaced separators back in
226 $items = explode( $separator, $cleaned );
227 foreach ( $items as $i => $str ) {
228 $items[$i] = str_replace( $placeholder, $separator, $str );
235 * More or less "markup-safe" str_replace()
236 * Ignores any instances of the separator inside `<...>`
237 * @param string $search
238 * @param string $replace
239 * @param string $text
242 static function replaceMarkup( $search, $replace, $text ) {
243 $placeholder = "\x00";
245 // Remove placeholder instances
246 $text = str_replace( $placeholder, '', $text );
248 // Replace instances of the separator inside HTML-like tags with the placeholder
249 $replacer = new DoubleReplacer( $search, $placeholder );
250 $cleaned = StringUtils
::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
252 // Explode, then put the replaced separators back in
253 $cleaned = str_replace( $search, $replace, $cleaned );
254 $text = str_replace( $placeholder, $search, $cleaned );
260 * Escape a string to make it suitable for inclusion in a preg_replace()
261 * replacement parameter.
263 * @param string $string
266 static function escapeRegexReplacement( $string ) {
267 $string = str_replace( '\\', '\\\\', $string );
268 $string = str_replace( '$', '\\$', $string );
273 * Workalike for explode() with limited memory usage.
275 * @param string $separator
276 * @param string $subject
277 * @return ArrayIterator|ExplodeIterator
279 static function explode( $separator, $subject ) {
280 if ( substr_count( $subject, $separator ) > 1000 ) {
281 return new ExplodeIterator( $separator, $subject );
283 return new ArrayIterator( explode( $separator, $subject ) );