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.
29 * Test whether a string is valid UTF-8.
31 * The function check for invalid byte sequences, overlong encoding but
32 * not for different normalisations.
34 * This relies internally on the mbstring function mb_check_encoding()
35 * hardcoded to check against UTF-8. Whenever the function is not available
36 * we fallback to a pure PHP implementation. Setting $disableMbstring to
37 * true will skip the use of mb_check_encoding, this is mostly intended for
38 * unit testing our internal implementation.
42 * @param string $value String to check
43 * @param boolean $disableMbstring Whether to use the pure PHP
44 * implementation instead of trying mb_check_encoding. Intended for unit
45 * testing. Default: false
47 * @return boolean Whether the given $value is a valid UTF-8 encoded string
49 static function isUtf8( $value, $disableMbstring = false ) {
51 if ( preg_match( '/[\x80-\xff]/', $value ) === 0 ) {
52 # no high bit set, this is pure ASCII which is de facto
57 if ( !$disableMbstring && function_exists( 'mb_check_encoding' ) ) {
58 return mb_check_encoding( $value, 'UTF-8' );
60 $hasUtf8 = preg_match( '/^(?>
62 | [\xc0-\xdf][\x80-\xbf]
63 | [\xe0-\xef][\x80-\xbf]{2}
64 | [\xf0-\xf7][\x80-\xbf]{3}
65 | [\xf8-\xfb][\x80-\xbf]{4}
66 | \xfc[\x84-\xbf][\x80-\xbf]{4}
68 return ($hasUtf8 > 0 );
73 * Perform an operation equivalent to
75 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
77 * except that it's worst-case O(N) instead of O(N^2)
79 * Compared to delimiterReplace(), this implementation is fast but memory-
80 * hungry and inflexible. The memory requirements are such that I don't
81 * recommend using it on anything but guaranteed small chunks of text.
90 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
91 $segments = explode( $startDelim, $subject );
92 $output = array_shift( $segments );
93 foreach ( $segments as $s ) {
94 $endDelimPos = strpos( $s, $endDelim );
95 if ( $endDelimPos === false ) {
96 $output .= $startDelim . $s;
98 $output .= $replace . substr( $s, $endDelimPos +
strlen( $endDelim ) );
105 * Perform an operation equivalent to
107 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
109 * This implementation is slower than hungryDelimiterReplace but uses far less
110 * memory. The delimiters are literal strings, not regular expressions.
112 * If the start delimiter ends with an initial substring of the end delimiter,
113 * e.g. in the case of C-style comments, the behavior differs from the model
114 * regex. In this implementation, the end must share no characters with the
115 * start, so e.g. /*\/ is not considered to be both the start and end of a
116 * comment. /*\/xy/*\/ is considered to be a single comment with contents /xy/.
118 * @param string $startDelim start delimiter
119 * @param string $endDelim end delimiter
120 * @param $callback Callback: function to call on each match
121 * @param $subject String
122 * @param string $flags regular expression flags
123 * @throws MWException
126 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
131 $encStart = preg_quote( $startDelim, '!' );
132 $encEnd = preg_quote( $endDelim, '!' );
133 $strcmp = strpos( $flags, 'i' ) === false ?
'strcmp' : 'strcasecmp';
134 $endLength = strlen( $endDelim );
137 while ( $inputPos < strlen( $subject ) &&
138 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE
, $inputPos ) )
140 $tokenOffset = $m[0][1];
141 if ( $m[1][0] != '' ) {
143 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0 )
145 # An end match is present at the same location
147 $tokenLength = $endLength;
149 $tokenType = 'start';
150 $tokenLength = strlen( $m[0][0] );
152 } elseif ( $m[2][0] != '' ) {
154 $tokenLength = strlen( $m[0][0] );
156 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
159 if ( $tokenType == 'start' ) {
160 # Only move the start position if we haven't already found a start
161 # This means that START START END matches outer pair
162 if ( !$foundStart ) {
164 $inputPos = $tokenOffset +
$tokenLength;
165 # Write out the non-matching section
166 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
167 $outputPos = $tokenOffset;
168 $contentPos = $inputPos;
171 # Move the input position past the *first character* of START,
172 # to protect against missing END when it overlaps with START
173 $inputPos = $tokenOffset +
1;
175 } elseif ( $tokenType == 'end' ) {
178 $output .= call_user_func( $callback, array(
179 substr( $subject, $outputPos, $tokenOffset +
$tokenLength - $outputPos ),
180 substr( $subject, $contentPos, $tokenOffset - $contentPos )
184 # Non-matching end, write it out
185 $output .= substr( $subject, $inputPos, $tokenOffset +
$tokenLength - $outputPos );
187 $inputPos = $outputPos = $tokenOffset +
$tokenLength;
189 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
192 if ( $outputPos < strlen( $subject ) ) {
193 $output .= substr( $subject, $outputPos );
199 * Perform an operation equivalent to
201 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
203 * @param string $startDelim start delimiter regular expression
204 * @param string $endDelim end delimiter regular expression
205 * @param string $replace replacement string. May contain $1, which will be
206 * replaced by the text between the delimiters
207 * @param string $subject to search
208 * @param string $flags regular expression flags
209 * @return String: The string with the matches replaced
211 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
212 $replacer = new RegexlikeReplacer( $replace );
213 return self
::delimiterReplaceCallback( $startDelim, $endDelim,
214 $replacer->cb(), $subject, $flags );
218 * More or less "markup-safe" explode()
219 * Ignores any instances of the separator inside <...>
220 * @param $separator String
221 * @param $text String
224 static function explodeMarkup( $separator, $text ) {
225 $placeholder = "\x00";
227 // Remove placeholder instances
228 $text = str_replace( $placeholder, '', $text );
230 // Replace instances of the separator inside HTML-like tags with the placeholder
231 $replacer = new DoubleReplacer( $separator, $placeholder );
232 $cleaned = StringUtils
::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
234 // Explode, then put the replaced separators back in
235 $items = explode( $separator, $cleaned );
236 foreach( $items as $i => $str ) {
237 $items[$i] = str_replace( $placeholder, $separator, $str );
244 * Escape a string to make it suitable for inclusion in a preg_replace()
245 * replacement parameter.
247 * @param $string String
250 static function escapeRegexReplacement( $string ) {
251 $string = str_replace( '\\', '\\\\', $string );
252 $string = str_replace( '$', '\\$', $string );
257 * Workalike for explode() with limited memory usage.
258 * Returns an Iterator
261 * @return ArrayIterator|ExplodeIterator
263 static function explode( $separator, $subject ) {
264 if ( substr_count( $subject, $separator ) > 1000 ) {
265 return new ExplodeIterator( $separator, $subject );
267 return new ArrayIterator( explode( $separator, $subject ) );
273 * Base class for "replacers", objects used in preg_replace_callback() and
274 * StringUtils::delimiterReplaceCallback()
282 return array( &$this, 'replace' );
287 * Class to replace regex matches with a string similar to that used in preg_replace()
289 class RegexlikeReplacer
extends Replacer
{
295 function __construct( $r ) {
300 * @param $matches array
303 function replace( $matches ) {
305 foreach ( $matches as $i => $match ) {
306 $pairs["\$$i"] = $match;
308 return strtr( $this->r
, $pairs );
314 * Class to perform secondary replacement within each replacement string
316 class DoubleReplacer
extends Replacer
{
323 function __construct( $from, $to, $index = 0 ) {
326 $this->index
= $index;
330 * @param $matches array
333 function replace( $matches ) {
334 return str_replace( $this->from
, $this->to
, $matches[$this->index
] );
339 * Class to perform replacement based on a simple hashtable lookup
341 class HashtableReplacer
extends Replacer
{
348 function __construct( $table, $index = 0 ) {
349 $this->table
= $table;
350 $this->index
= $index;
354 * @param $matches array
357 function replace( $matches ) {
358 return $this->table
[$matches[$this->index
]];
363 * Replacement array for FSS with fallback to strtr()
364 * Supports lazy initialisation of FSS resource
366 class ReplacementArray
{
367 /*mostly private*/ var $data = false;
368 /*mostly private*/ var $fss = false;
371 * Create an object with the specified replacement array
372 * The array should have the same form as the replacement array for strtr()
375 function __construct( $data = array() ) {
383 return array( 'data' );
386 function __wakeup() {
391 * Set the whole replacement array at once
393 function setArray( $data ) {
401 function getArray() {
406 * Set an element of the replacement array
407 * @param $from string
410 function setPair( $from, $to ) {
411 $this->data
[$from] = $to;
418 function mergeArray( $data ) {
419 $this->data
= array_merge( $this->data
, $data );
426 function merge( $other ) {
427 $this->data
= array_merge( $this->data
, $other->data
);
432 * @param $from string
434 function removePair( $from ) {
435 unset( $this->data
[$from] );
442 function removeArray( $data ) {
443 foreach( $data as $from => $to ) {
444 $this->removePair( $from );
450 * @param $subject string
453 function replace( $subject ) {
454 if ( function_exists( 'fss_prep_replace' ) ) {
455 wfProfileIn( __METHOD__
. '-fss' );
456 if ( $this->fss
=== false ) {
457 $this->fss
= fss_prep_replace( $this->data
);
459 $result = fss_exec_replace( $this->fss
, $subject );
460 wfProfileOut( __METHOD__
. '-fss' );
462 wfProfileIn( __METHOD__
. '-strtr' );
463 $result = strtr( $subject, $this->data
);
464 wfProfileOut( __METHOD__
. '-strtr' );
471 * An iterator which works exactly like:
473 * foreach ( explode( $delim, $s ) as $element ) {
477 * Except it doesn't use 193 byte per element
479 class ExplodeIterator
implements Iterator
{
480 // The subject string
481 var $subject, $subjectLength;
484 var $delim, $delimLength;
486 // The position of the start of the line
489 // The position after the end of the next delimiter
496 * Construct a DelimIterator
497 * @param $delim string
500 function __construct( $delim, $s ) {
502 $this->delim
= $delim;
504 // Micro-optimisation (theoretical)
505 $this->subjectLength
= strlen( $s );
506 $this->delimLength
= strlen( $delim );
513 $this->endPos
= strpos( $this->subject
, $this->delim
);
514 $this->refreshCurrent();
517 function refreshCurrent() {
518 if ( $this->curPos
=== false ) {
519 $this->current
= false;
520 } elseif ( $this->curPos
>= $this->subjectLength
) {
522 } elseif ( $this->endPos
=== false ) {
523 $this->current
= substr( $this->subject
, $this->curPos
);
525 $this->current
= substr( $this->subject
, $this->curPos
, $this->endPos
- $this->curPos
);
530 return $this->current
;
534 return $this->curPos
;
541 if ( $this->endPos
=== false ) {
542 $this->curPos
= false;
544 $this->curPos
= $this->endPos +
$this->delimLength
;
545 if ( $this->curPos
>= $this->subjectLength
) {
546 $this->endPos
= false;
548 $this->endPos
= strpos( $this->subject
, $this->delim
, $this->curPos
);
551 $this->refreshCurrent();
552 return $this->current
;
559 return $this->curPos
!== false;