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.
41 * @note In MediaWiki 1.21, this function did not provide proper UTF-8 validation.
42 * In particular, the pure PHP code path did not in fact check for overlong forms.
43 * Beware of this when backporting code to that version of MediaWiki.
45 * @param string $value String to check
46 * @param boolean $disableMbstring Whether to use the pure PHP
47 * implementation instead of trying mb_check_encoding. Intended for unit
48 * testing. Default: false
50 * @return boolean Whether the given $value is a valid UTF-8 encoded string
52 static function isUtf8( $value, $disableMbstring = false ) {
53 $value = (string)$value;
54 if ( preg_match( "/[\x80-\xff]/S", $value ) === 0 ) {
55 // String contains only ASCII characters, has to be valid
59 // If the mbstring extension is loaded, use it. However, before PHP 5.4, values above
60 // U+10FFFF are incorrectly allowed, so we have to check for them separately.
61 if ( !$disableMbstring && function_exists( 'mb_check_encoding' ) ) {
63 if ( $newPHP === null ) {
64 $newPHP = !mb_check_encoding( "\xf4\x90\x80\x80", 'UTF-8' );
67 return mb_check_encoding( $value, 'UTF-8' ) &&
68 ( $newPHP ||
preg_match( "/\xf4[\x90-\xbf]|[\xf5-\xff]/S", $value ) === 0 );
71 // PCRE implements repetition using recursion; to avoid a stack overflow (and segfault)
72 // for large input, we check for invalid sequences (<= 5 bytes) rather than valid
73 // sequences, which can be as long as the input string is. Multiple short regexes are
74 // used rather than a single long regex for performance.
76 if ( $regexes === null ) {
77 $cont = "[\x80-\xbf]";
78 $after = "(?!$cont)"; // "(?:[^\x80-\xbf]|$)" would work here
80 // Continuation byte at the start
83 // ASCII byte followed by a continuation byte
84 "/[\\x00-\x7f]$cont/S",
87 "/[\xc0\xc1\xf5-\xff]/S",
89 // Invalid 2-byte sequence, or valid one then an extra continuation byte
90 "/[\xc2-\xdf](?!$cont$after)/S",
92 // Invalid 3-byte sequence, or valid one then an extra continuation byte
93 "/\xe0(?![\xa0-\xbf]$cont$after)/",
94 "/[\xe1-\xec\xee\xef](?!$cont{2}$after)/S",
95 "/\xed(?![\x80-\x9f]$cont$after)/",
97 // Invalid 4-byte sequence, or valid one then an extra continuation byte
98 "/\xf0(?![\x90-\xbf]$cont{2}$after)/",
99 "/[\xf1-\xf3](?!$cont{3}$after)/S",
100 "/\xf4(?![\x80-\x8f]$cont{2}$after)/",
104 foreach ( $regexes as $regex ) {
105 if ( preg_match( $regex, $value ) !== 0 ) {
113 * Perform an operation equivalent to
115 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
117 * except that it's worst-case O(N) instead of O(N^2)
119 * Compared to delimiterReplace(), this implementation is fast but memory-
120 * hungry and inflexible. The memory requirements are such that I don't
121 * recommend using it on anything but guaranteed small chunks of text.
130 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
131 $segments = explode( $startDelim, $subject );
132 $output = array_shift( $segments );
133 foreach ( $segments as $s ) {
134 $endDelimPos = strpos( $s, $endDelim );
135 if ( $endDelimPos === false ) {
136 $output .= $startDelim . $s;
138 $output .= $replace . substr( $s, $endDelimPos +
strlen( $endDelim ) );
145 * Perform an operation equivalent to
147 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
149 * This implementation is slower than hungryDelimiterReplace but uses far less
150 * memory. The delimiters are literal strings, not regular expressions.
152 * If the start delimiter ends with an initial substring of the end delimiter,
153 * e.g. in the case of C-style comments, the behavior differs from the model
154 * regex. In this implementation, the end must share no characters with the
155 * start, so e.g. /*\/ is not considered to be both the start and end of a
156 * comment. /*\/xy/*\/ is considered to be a single comment with contents /xy/.
158 * @param string $startDelim start delimiter
159 * @param string $endDelim end delimiter
160 * @param $callback Callback: function to call on each match
161 * @param $subject String
162 * @param string $flags regular expression flags
163 * @throws MWException
166 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
171 $encStart = preg_quote( $startDelim, '!' );
172 $encEnd = preg_quote( $endDelim, '!' );
173 $strcmp = strpos( $flags, 'i' ) === false ?
'strcmp' : 'strcasecmp';
174 $endLength = strlen( $endDelim );
177 while ( $inputPos < strlen( $subject ) &&
178 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE
, $inputPos ) )
180 $tokenOffset = $m[0][1];
181 if ( $m[1][0] != '' ) {
183 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0 )
185 # An end match is present at the same location
187 $tokenLength = $endLength;
189 $tokenType = 'start';
190 $tokenLength = strlen( $m[0][0] );
192 } elseif ( $m[2][0] != '' ) {
194 $tokenLength = strlen( $m[0][0] );
196 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
199 if ( $tokenType == 'start' ) {
200 # Only move the start position if we haven't already found a start
201 # This means that START START END matches outer pair
202 if ( !$foundStart ) {
204 $inputPos = $tokenOffset +
$tokenLength;
205 # Write out the non-matching section
206 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
207 $outputPos = $tokenOffset;
208 $contentPos = $inputPos;
211 # Move the input position past the *first character* of START,
212 # to protect against missing END when it overlaps with START
213 $inputPos = $tokenOffset +
1;
215 } elseif ( $tokenType == 'end' ) {
218 $output .= call_user_func( $callback, array(
219 substr( $subject, $outputPos, $tokenOffset +
$tokenLength - $outputPos ),
220 substr( $subject, $contentPos, $tokenOffset - $contentPos )
224 # Non-matching end, write it out
225 $output .= substr( $subject, $inputPos, $tokenOffset +
$tokenLength - $outputPos );
227 $inputPos = $outputPos = $tokenOffset +
$tokenLength;
229 throw new MWException( 'Invalid delimiter given to ' . __METHOD__
);
232 if ( $outputPos < strlen( $subject ) ) {
233 $output .= substr( $subject, $outputPos );
239 * Perform an operation equivalent to
241 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
243 * @param string $startDelim start delimiter regular expression
244 * @param string $endDelim end delimiter regular expression
245 * @param string $replace replacement string. May contain $1, which will be
246 * replaced by the text between the delimiters
247 * @param string $subject to search
248 * @param string $flags regular expression flags
249 * @return String: The string with the matches replaced
251 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
252 $replacer = new RegexlikeReplacer( $replace );
253 return self
::delimiterReplaceCallback( $startDelim, $endDelim,
254 $replacer->cb(), $subject, $flags );
258 * More or less "markup-safe" explode()
259 * Ignores any instances of the separator inside <...>
260 * @param $separator String
261 * @param $text String
264 static function explodeMarkup( $separator, $text ) {
265 $placeholder = "\x00";
267 // Remove placeholder instances
268 $text = str_replace( $placeholder, '', $text );
270 // Replace instances of the separator inside HTML-like tags with the placeholder
271 $replacer = new DoubleReplacer( $separator, $placeholder );
272 $cleaned = StringUtils
::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
274 // Explode, then put the replaced separators back in
275 $items = explode( $separator, $cleaned );
276 foreach ( $items as $i => $str ) {
277 $items[$i] = str_replace( $placeholder, $separator, $str );
284 * Escape a string to make it suitable for inclusion in a preg_replace()
285 * replacement parameter.
287 * @param $string String
290 static function escapeRegexReplacement( $string ) {
291 $string = str_replace( '\\', '\\\\', $string );
292 $string = str_replace( '$', '\\$', $string );
297 * Workalike for explode() with limited memory usage.
298 * Returns an Iterator
301 * @return ArrayIterator|ExplodeIterator
303 static function explode( $separator, $subject ) {
304 if ( substr_count( $subject, $separator ) > 1000 ) {
305 return new ExplodeIterator( $separator, $subject );
307 return new ArrayIterator( explode( $separator, $subject ) );
313 * Base class for "replacers", objects used in preg_replace_callback() and
314 * StringUtils::delimiterReplaceCallback()
322 return array( &$this, 'replace' );
327 * Class to replace regex matches with a string similar to that used in preg_replace()
329 class RegexlikeReplacer
extends Replacer
{
335 function __construct( $r ) {
340 * @param $matches array
343 function replace( $matches ) {
345 foreach ( $matches as $i => $match ) {
346 $pairs["\$$i"] = $match;
348 return strtr( $this->r
, $pairs );
354 * Class to perform secondary replacement within each replacement string
356 class DoubleReplacer
extends Replacer
{
363 function __construct( $from, $to, $index = 0 ) {
366 $this->index
= $index;
370 * @param $matches array
373 function replace( $matches ) {
374 return str_replace( $this->from
, $this->to
, $matches[$this->index
] );
379 * Class to perform replacement based on a simple hashtable lookup
381 class HashtableReplacer
extends Replacer
{
388 function __construct( $table, $index = 0 ) {
389 $this->table
= $table;
390 $this->index
= $index;
394 * @param $matches array
397 function replace( $matches ) {
398 return $this->table
[$matches[$this->index
]];
403 * Replacement array for FSS with fallback to strtr()
404 * Supports lazy initialisation of FSS resource
406 class ReplacementArray
{
407 /*mostly private*/ var $data = false;
408 /*mostly private*/ var $fss = false;
411 * Create an object with the specified replacement array
412 * The array should have the same form as the replacement array for strtr()
415 function __construct( $data = array() ) {
423 return array( 'data' );
426 function __wakeup() {
431 * Set the whole replacement array at once
433 function setArray( $data ) {
441 function getArray() {
446 * Set an element of the replacement array
447 * @param $from string
450 function setPair( $from, $to ) {
451 $this->data
[$from] = $to;
458 function mergeArray( $data ) {
459 $this->data
= array_merge( $this->data
, $data );
466 function merge( $other ) {
467 $this->data
= array_merge( $this->data
, $other->data
);
472 * @param $from string
474 function removePair( $from ) {
475 unset( $this->data
[$from] );
482 function removeArray( $data ) {
483 foreach ( $data as $from => $to ) {
484 $this->removePair( $from );
490 * @param $subject string
493 function replace( $subject ) {
494 if ( function_exists( 'fss_prep_replace' ) ) {
495 wfProfileIn( __METHOD__
. '-fss' );
496 if ( $this->fss
=== false ) {
497 $this->fss
= fss_prep_replace( $this->data
);
499 $result = fss_exec_replace( $this->fss
, $subject );
500 wfProfileOut( __METHOD__
. '-fss' );
502 wfProfileIn( __METHOD__
. '-strtr' );
503 $result = strtr( $subject, $this->data
);
504 wfProfileOut( __METHOD__
. '-strtr' );
511 * An iterator which works exactly like:
513 * foreach ( explode( $delim, $s ) as $element ) {
517 * Except it doesn't use 193 byte per element
519 class ExplodeIterator
implements Iterator
{
520 // The subject string
521 var $subject, $subjectLength;
524 var $delim, $delimLength;
526 // The position of the start of the line
529 // The position after the end of the next delimiter
536 * Construct a DelimIterator
537 * @param $delim string
540 function __construct( $delim, $s ) {
542 $this->delim
= $delim;
544 // Micro-optimisation (theoretical)
545 $this->subjectLength
= strlen( $s );
546 $this->delimLength
= strlen( $delim );
553 $this->endPos
= strpos( $this->subject
, $this->delim
);
554 $this->refreshCurrent();
557 function refreshCurrent() {
558 if ( $this->curPos
=== false ) {
559 $this->current
= false;
560 } elseif ( $this->curPos
>= $this->subjectLength
) {
562 } elseif ( $this->endPos
=== false ) {
563 $this->current
= substr( $this->subject
, $this->curPos
);
565 $this->current
= substr( $this->subject
, $this->curPos
, $this->endPos
- $this->curPos
);
570 return $this->current
;
574 return $this->curPos
;
581 if ( $this->endPos
=== false ) {
582 $this->curPos
= false;
584 $this->curPos
= $this->endPos +
$this->delimLength
;
585 if ( $this->curPos
>= $this->subjectLength
) {
586 $this->endPos
= false;
588 $this->endPos
= strpos( $this->subject
, $this->delim
, $this->curPos
);
591 $this->refreshCurrent();
592 return $this->current
;
599 return $this->curPos
!== false;