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 * Perform an operation equivalent to
30 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
32 * except that it's worst-case O(N) instead of O(N^2)
34 * Compared to delimiterReplace(), this implementation is fast but memory-
35 * hungry and inflexible. The memory requirements are such that I don't
36 * recommend using it on anything but guaranteed small chunks of text.
45 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
46 $segments = explode( $startDelim, $subject );
47 $output = array_shift( $segments );
48 foreach ( $segments as $s ) {
49 $endDelimPos = strpos( $s, $endDelim );
50 if ( $endDelimPos === false ) {
51 $output .= $startDelim . $s;
53 $output .= $replace . substr( $s, $endDelimPos +
strlen( $endDelim ) );
60 * Perform an operation equivalent to
62 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
64 * This implementation is slower than hungryDelimiterReplace but uses far less
65 * memory. The delimiters are literal strings, not regular expressions.
67 * If the start delimiter ends with an initial substring of the end delimiter,
68 * e.g. in the case of C-style comments, the behaviour differs from the model
69 * regex. In this implementation, the end must share no characters with the
70 * start, so e.g. /*\/ is not considered to be both the start and end of a
71 * comment. /*\/xy/*\/ is considered to be a single comment with contents /xy/.
73 * @param $startDelim String: start delimiter
74 * @param $endDelim String: end delimiter
75 * @param $callback Callback: function to call on each match
76 * @param $subject String
77 * @param $flags String: regular expression flags
81 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
86 $encStart = preg_quote( $startDelim, '!' );
87 $encEnd = preg_quote( $endDelim, '!' );
88 $strcmp = strpos( $flags, 'i' ) === false ?
'strcmp' : 'strcasecmp';
89 $endLength = strlen( $endDelim );
92 while ( $inputPos < strlen( $subject ) &&
93 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE
, $inputPos ) )
95 $tokenOffset = $m[0][1];
96 if ( $m[1][0] != '' ) {
98 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0 )
100 # An end match is present at the same location
102 $tokenLength = $endLength;
104 $tokenType = 'start';
105 $tokenLength = strlen( $m[0][0] );
107 } elseif ( $m[2][0] != '' ) {
109 $tokenLength = strlen( $m[0][0] );
111 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
114 if ( $tokenType == 'start' ) {
115 # Only move the start position if we haven't already found a start
116 # This means that START START END matches outer pair
117 if ( !$foundStart ) {
119 $inputPos = $tokenOffset +
$tokenLength;
120 # Write out the non-matching section
121 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
122 $outputPos = $tokenOffset;
123 $contentPos = $inputPos;
126 # Move the input position past the *first character* of START,
127 # to protect against missing END when it overlaps with START
128 $inputPos = $tokenOffset +
1;
130 } elseif ( $tokenType == 'end' ) {
133 $output .= call_user_func( $callback, array(
134 substr( $subject, $outputPos, $tokenOffset +
$tokenLength - $outputPos ),
135 substr( $subject, $contentPos, $tokenOffset - $contentPos )
139 # Non-matching end, write it out
140 $output .= substr( $subject, $inputPos, $tokenOffset +
$tokenLength - $outputPos );
142 $inputPos = $outputPos = $tokenOffset +
$tokenLength;
144 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
147 if ( $outputPos < strlen( $subject ) ) {
148 $output .= substr( $subject, $outputPos );
154 * Perform an operation equivalent to
156 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
158 * @param $startDelim String: start delimiter regular expression
159 * @param $endDelim String: end delimiter regular expression
160 * @param $replace String: replacement string. May contain $1, which will be
161 * replaced by the text between the delimiters
162 * @param $subject String to search
163 * @param $flags String: regular expression flags
164 * @return String: The string with the matches replaced
166 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
167 $replacer = new RegexlikeReplacer( $replace );
168 return self
::delimiterReplaceCallback( $startDelim, $endDelim,
169 $replacer->cb(), $subject, $flags );
173 * More or less "markup-safe" explode()
174 * Ignores any instances of the separator inside <...>
175 * @param $separator String
176 * @param $text String
179 static function explodeMarkup( $separator, $text ) {
180 $placeholder = "\x00";
182 // Remove placeholder instances
183 $text = str_replace( $placeholder, '', $text );
185 // Replace instances of the separator inside HTML-like tags with the placeholder
186 $replacer = new DoubleReplacer( $separator, $placeholder );
187 $cleaned = StringUtils
::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
189 // Explode, then put the replaced separators back in
190 $items = explode( $separator, $cleaned );
191 foreach( $items as $i => $str ) {
192 $items[$i] = str_replace( $placeholder, $separator, $str );
199 * Escape a string to make it suitable for inclusion in a preg_replace()
200 * replacement parameter.
202 * @param $string String
205 static function escapeRegexReplacement( $string ) {
206 $string = str_replace( '\\', '\\\\', $string );
207 $string = str_replace( '$', '\\$', $string );
212 * Workalike for explode() with limited memory usage.
213 * Returns an Iterator
216 * @return ArrayIterator|ExplodeIterator
218 static function explode( $separator, $subject ) {
219 if ( substr_count( $subject, $separator ) > 1000 ) {
220 return new ExplodeIterator( $separator, $subject );
222 return new ArrayIterator( explode( $separator, $subject ) );
228 * Base class for "replacers", objects used in preg_replace_callback() and
229 * StringUtils::delimiterReplaceCallback()
237 return array( &$this, 'replace' );
242 * Class to replace regex matches with a string similar to that used in preg_replace()
244 class RegexlikeReplacer
extends Replacer
{
250 function __construct( $r ) {
255 * @param $matches array
258 function replace( $matches ) {
260 foreach ( $matches as $i => $match ) {
261 $pairs["\$$i"] = $match;
263 return strtr( $this->r
, $pairs );
269 * Class to perform secondary replacement within each replacement string
271 class DoubleReplacer
extends Replacer
{
278 function __construct( $from, $to, $index = 0 ) {
281 $this->index
= $index;
285 * @param $matches array
288 function replace( $matches ) {
289 return str_replace( $this->from
, $this->to
, $matches[$this->index
] );
294 * Class to perform replacement based on a simple hashtable lookup
296 class HashtableReplacer
extends Replacer
{
303 function __construct( $table, $index = 0 ) {
304 $this->table
= $table;
305 $this->index
= $index;
309 * @param $matches array
312 function replace( $matches ) {
313 return $this->table
[$matches[$this->index
]];
318 * Replacement array for FSS with fallback to strtr()
319 * Supports lazy initialisation of FSS resource
321 class ReplacementArray
{
322 /*mostly private*/ var $data = false;
323 /*mostly private*/ var $fss = false;
326 * Create an object with the specified replacement array
327 * The array should have the same form as the replacement array for strtr()
330 function __construct( $data = array() ) {
338 return array( 'data' );
341 function __wakeup() {
346 * Set the whole replacement array at once
348 function setArray( $data ) {
356 function getArray() {
361 * Set an element of the replacement array
362 * @param $from string
365 function setPair( $from, $to ) {
366 $this->data
[$from] = $to;
373 function mergeArray( $data ) {
374 $this->data
= array_merge( $this->data
, $data );
381 function merge( $other ) {
382 $this->data
= array_merge( $this->data
, $other->data
);
387 * @param $from string
389 function removePair( $from ) {
390 unset($this->data
[$from]);
397 function removeArray( $data ) {
398 foreach( $data as $from => $to ) {
399 $this->removePair( $from );
405 * @param $subject string
408 function replace( $subject ) {
409 if ( function_exists( 'fss_prep_replace' ) ) {
410 wfProfileIn( __METHOD__
.'-fss' );
411 if ( $this->fss
=== false ) {
412 $this->fss
= fss_prep_replace( $this->data
);
414 $result = fss_exec_replace( $this->fss
, $subject );
415 wfProfileOut( __METHOD__
.'-fss' );
417 wfProfileIn( __METHOD__
.'-strtr' );
418 $result = strtr( $subject, $this->data
);
419 wfProfileOut( __METHOD__
.'-strtr' );
426 * An iterator which works exactly like:
428 * foreach ( explode( $delim, $s ) as $element ) {
432 * Except it doesn't use 193 byte per element
434 class ExplodeIterator
implements Iterator
{
435 // The subject string
436 var $subject, $subjectLength;
439 var $delim, $delimLength;
441 // The position of the start of the line
444 // The position after the end of the next delimiter
451 * Construct a DelimIterator
452 * @param $delim string
455 function __construct( $delim, $s ) {
457 $this->delim
= $delim;
459 // Micro-optimisation (theoretical)
460 $this->subjectLength
= strlen( $s );
461 $this->delimLength
= strlen( $delim );
468 $this->endPos
= strpos( $this->subject
, $this->delim
);
469 $this->refreshCurrent();
472 function refreshCurrent() {
473 if ( $this->curPos
=== false ) {
474 $this->current
= false;
475 } elseif ( $this->curPos
>= $this->subjectLength
) {
477 } elseif ( $this->endPos
=== false ) {
478 $this->current
= substr( $this->subject
, $this->curPos
);
480 $this->current
= substr( $this->subject
, $this->curPos
, $this->endPos
- $this->curPos
);
485 return $this->current
;
489 return $this->curPos
;
496 if ( $this->endPos
=== false ) {
497 $this->curPos
= false;
499 $this->curPos
= $this->endPos +
$this->delimLength
;
500 if ( $this->curPos
>= $this->subjectLength
) {
501 $this->endPos
= false;
503 $this->endPos
= strpos( $this->subject
, $this->delim
, $this->curPos
);
506 $this->refreshCurrent();
507 return $this->current
;
514 return $this->curPos
!== false;