Follow-up r70037: Fix ApiUpload by passing a WebRequestUpload to the the initializer
[mediawiki.git] / includes / StringUtils.php
blob6c8412f2102589cc6a24fc0945d3568345a8b902
1 <?php
2 /**
3 * A collection of static methods to play with strings.
4 */
5 class StringUtils {
6 /**
7 * Perform an operation equivalent to
9 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
11 * except that it's worst-case O(N) instead of O(N^2)
13 * Compared to delimiterReplace(), this implementation is fast but memory-
14 * hungry and inflexible. The memory requirements are such that I don't
15 * recommend using it on anything but guaranteed small chunks of text.
17 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
18 $segments = explode( $startDelim, $subject );
19 $output = array_shift( $segments );
20 foreach ( $segments as $s ) {
21 $endDelimPos = strpos( $s, $endDelim );
22 if ( $endDelimPos === false ) {
23 $output .= $startDelim . $s;
24 } else {
25 $output .= $replace . substr( $s, $endDelimPos + strlen( $endDelim ) );
28 return $output;
31 /**
32 * Perform an operation equivalent to
34 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
36 * This implementation is slower than hungryDelimiterReplace but uses far less
37 * memory. The delimiters are literal strings, not regular expressions.
39 * @param $startDelim String: start delimiter
40 * @param $endDelim String: end delimiter
41 * @param $callback Callback: function to call on each match
42 * @param $subject String
43 * @param $flags String: regular expression flags
45 # If the start delimiter ends with an initial substring of the end delimiter,
46 # e.g. in the case of C-style comments, the behaviour differs from the model
47 # regex. In this implementation, the end must share no characters with the
48 # start, so e.g. /*/ is not considered to be both the start and end of a
49 # comment. /*/xy/*/ is considered to be a single comment with contents /xy/.
50 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
51 $inputPos = 0;
52 $outputPos = 0;
53 $output = '';
54 $foundStart = false;
55 $encStart = preg_quote( $startDelim, '!' );
56 $encEnd = preg_quote( $endDelim, '!' );
57 $strcmp = strpos( $flags, 'i' ) === false ? 'strcmp' : 'strcasecmp';
58 $endLength = strlen( $endDelim );
59 $m = array();
61 while ( $inputPos < strlen( $subject ) &&
62 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE, $inputPos ) )
64 $tokenOffset = $m[0][1];
65 if ( $m[1][0] != '' ) {
66 if ( $foundStart &&
67 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0 )
69 # An end match is present at the same location
70 $tokenType = 'end';
71 $tokenLength = $endLength;
72 } else {
73 $tokenType = 'start';
74 $tokenLength = strlen( $m[0][0] );
76 } elseif ( $m[2][0] != '' ) {
77 $tokenType = 'end';
78 $tokenLength = strlen( $m[0][0] );
79 } else {
80 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
83 if ( $tokenType == 'start' ) {
84 $inputPos = $tokenOffset + $tokenLength;
85 # Only move the start position if we haven't already found a start
86 # This means that START START END matches outer pair
87 if ( !$foundStart ) {
88 # Found start
89 # Write out the non-matching section
90 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
91 $outputPos = $tokenOffset;
92 $contentPos = $inputPos;
93 $foundStart = true;
95 } elseif ( $tokenType == 'end' ) {
96 if ( $foundStart ) {
97 # Found match
98 $output .= call_user_func( $callback, array(
99 substr( $subject, $outputPos, $tokenOffset + $tokenLength - $outputPos ),
100 substr( $subject, $contentPos, $tokenOffset - $contentPos )
102 $foundStart = false;
103 } else {
104 # Non-matching end, write it out
105 $output .= substr( $subject, $inputPos, $tokenOffset + $tokenLength - $outputPos );
107 $inputPos = $outputPos = $tokenOffset + $tokenLength;
108 } else {
109 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
112 if ( $outputPos < strlen( $subject ) ) {
113 $output .= substr( $subject, $outputPos );
115 return $output;
119 * Perform an operation equivalent to
121 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
123 * @param $startDelim String: start delimiter regular expression
124 * @param $endDelim String: end delimiter regular expression
125 * @param $replace String: replacement string. May contain $1, which will be
126 * replaced by the text between the delimiters
127 * @param $subject String to search
128 * @return String: The string with the matches replaced
130 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
131 $replacer = new RegexlikeReplacer( $replace );
132 return self::delimiterReplaceCallback( $startDelim, $endDelim,
133 $replacer->cb(), $subject, $flags );
137 * More or less "markup-safe" explode()
138 * Ignores any instances of the separator inside <...>
139 * @param $separator String
140 * @param $text String
141 * @return array
143 static function explodeMarkup( $separator, $text ) {
144 $placeholder = "\x00";
146 // Remove placeholder instances
147 $text = str_replace( $placeholder, '', $text );
149 // Replace instances of the separator inside HTML-like tags with the placeholder
150 $replacer = new DoubleReplacer( $separator, $placeholder );
151 $cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
153 // Explode, then put the replaced separators back in
154 $items = explode( $separator, $cleaned );
155 foreach( $items as $i => $str ) {
156 $items[$i] = str_replace( $placeholder, $separator, $str );
159 return $items;
163 * Escape a string to make it suitable for inclusion in a preg_replace()
164 * replacement parameter.
166 * @param $string String
167 * @return String
169 static function escapeRegexReplacement( $string ) {
170 $string = str_replace( '\\', '\\\\', $string );
171 $string = str_replace( '$', '\\$', $string );
172 return $string;
176 * Workalike for explode() with limited memory usage.
177 * Returns an Iterator
179 static function explode( $separator, $subject ) {
180 if ( substr_count( $subject, $separator ) > 1000 ) {
181 return new ExplodeIterator( $separator, $subject );
182 } else {
183 return new ArrayIterator( explode( $separator, $subject ) );
189 * Base class for "replacers", objects used in preg_replace_callback() and
190 * StringUtils::delimiterReplaceCallback()
192 class Replacer {
193 function cb() {
194 return array( &$this, 'replace' );
199 * Class to replace regex matches with a string similar to that used in preg_replace()
201 class RegexlikeReplacer extends Replacer {
202 var $r;
203 function __construct( $r ) {
204 $this->r = $r;
207 function replace( $matches ) {
208 $pairs = array();
209 foreach ( $matches as $i => $match ) {
210 $pairs["\$$i"] = $match;
212 return strtr( $this->r, $pairs );
218 * Class to perform secondary replacement within each replacement string
220 class DoubleReplacer extends Replacer {
221 function __construct( $from, $to, $index = 0 ) {
222 $this->from = $from;
223 $this->to = $to;
224 $this->index = $index;
227 function replace( $matches ) {
228 return str_replace( $this->from, $this->to, $matches[$this->index] );
233 * Class to perform replacement based on a simple hashtable lookup
235 class HashtableReplacer extends Replacer {
236 var $table, $index;
238 function __construct( $table, $index = 0 ) {
239 $this->table = $table;
240 $this->index = $index;
243 function replace( $matches ) {
244 return $this->table[$matches[$this->index]];
249 * Replacement array for FSS with fallback to strtr()
250 * Supports lazy initialisation of FSS resource
252 class ReplacementArray {
253 /*mostly private*/ var $data = false;
254 /*mostly private*/ var $fss = false;
257 * Create an object with the specified replacement array
258 * The array should have the same form as the replacement array for strtr()
260 function __construct( $data = array() ) {
261 $this->data = $data;
264 function __sleep() {
265 return array( 'data' );
268 function __wakeup() {
269 $this->fss = false;
273 * Set the whole replacement array at once
275 function setArray( $data ) {
276 $this->data = $data;
277 $this->fss = false;
280 function getArray() {
281 return $this->data;
285 * Set an element of the replacement array
287 function setPair( $from, $to ) {
288 $this->data[$from] = $to;
289 $this->fss = false;
292 function mergeArray( $data ) {
293 $this->data = array_merge( $this->data, $data );
294 $this->fss = false;
297 function merge( $other ) {
298 $this->data = array_merge( $this->data, $other->data );
299 $this->fss = false;
302 function removePair( $from ) {
303 unset($this->data[$from]);
304 $this->fss = false;
307 function removeArray( $data ) {
308 foreach( $data as $from => $to )
309 $this->removePair( $from );
310 $this->fss = false;
313 function replace( $subject ) {
314 if ( function_exists( 'fss_prep_replace' ) ) {
315 wfProfileIn( __METHOD__.'-fss' );
316 if ( $this->fss === false ) {
317 $this->fss = fss_prep_replace( $this->data );
319 $result = fss_exec_replace( $this->fss, $subject );
320 wfProfileOut( __METHOD__.'-fss' );
321 } else {
322 wfProfileIn( __METHOD__.'-strtr' );
323 $result = strtr( $subject, $this->data );
324 wfProfileOut( __METHOD__.'-strtr' );
326 return $result;
331 * An iterator which works exactly like:
333 * foreach ( explode( $delim, $s ) as $element ) {
334 * ...
337 * Except it doesn't use 193 byte per element
339 class ExplodeIterator implements Iterator {
340 // The subject string
341 var $subject, $subjectLength;
343 // The delimiter
344 var $delim, $delimLength;
346 // The position of the start of the line
347 var $curPos;
349 // The position after the end of the next delimiter
350 var $endPos;
352 // The current token
353 var $current;
355 /**
356 * Construct a DelimIterator
358 function __construct( $delim, $s ) {
359 $this->subject = $s;
360 $this->delim = $delim;
362 // Micro-optimisation (theoretical)
363 $this->subjectLength = strlen( $s );
364 $this->delimLength = strlen( $delim );
366 $this->rewind();
369 function rewind() {
370 $this->curPos = 0;
371 $this->endPos = strpos( $this->subject, $this->delim );
372 $this->refreshCurrent();
376 function refreshCurrent() {
377 if ( $this->curPos === false ) {
378 $this->current = false;
379 } elseif ( $this->curPos >= $this->subjectLength ) {
380 $this->current = '';
381 } elseif ( $this->endPos === false ) {
382 $this->current = substr( $this->subject, $this->curPos );
383 } else {
384 $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos );
388 function current() {
389 return $this->current;
392 function key() {
393 return $this->curPos;
396 function next() {
397 if ( $this->endPos === false ) {
398 $this->curPos = false;
399 } else {
400 $this->curPos = $this->endPos + $this->delimLength;
401 if ( $this->curPos >= $this->subjectLength ) {
402 $this->endPos = false;
403 } else {
404 $this->endPos = strpos( $this->subject, $this->delim, $this->curPos );
407 $this->refreshCurrent();
408 return $this->current;
411 function valid() {
412 return $this->curPos !== false;