Collection of generic string functions and classes
[lhc/web/wiklou.git] / includes / StringUtils.php
1 <?php
2
3 class StringUtils {
4 /**
5 * Perform an operation equivalent to
6 *
7 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
8 *
9 * except that it's worst-case O(N) instead of O(N^2)
10 *
11 * Compared to delimiterReplace(), this implementation is fast but memory-
12 * hungry and inflexible. The memory requirements are such that I don't
13 * recommend using it on anything but guaranteed small chunks of text.
14 */
15 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
16 $segments = explode( $startDelim, $subject );
17 $output = array_shift( $segments );
18 foreach ( $segments as $s ) {
19 $endDelimPos = strpos( $s, $endDelim );
20 if ( $endDelimPos === false ) {
21 $output .= $startDelim . $s;
22 } else {
23 $output .= $replace . substr( $s, $endDelimPos + strlen( $endDelim ) );
24 }
25 }
26 return $output;
27 }
28
29 /**
30 * Perform an operation equivalent to
31 *
32 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
33 *
34 * This implementation is slower than staticDelimiterReplace but uses far less
35 * memory and allows regular expression delimiters.
36 *
37 * @param string $flags Regular expression flags
38 */
39 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
40 $inputPos = 0;
41 $outputPos = 0;
42 $output = '';
43 $foundStart = false;
44
45 while ( $inputPos < strlen( $subject ) &&
46 preg_match( "!($startDelim)|($endDelim)!$flags", $subject, $m, PREG_OFFSET_CAPTURE, $inputPos ) )
47 {
48 if ( $m[1][0] != '' ) {
49 # Found start
50 # Write out the non-matching section
51 $output .= substr( $subject, $outputPos, $m[1][1] - $outputPos );
52 $foundStart = true;
53 $inputPos = $contentPos = $m[1][1] + strlen( $m[1][0] );
54 $outputPos = $m[1][1];
55 } elseif ( $m[2][0] != '' ) {
56 # Found end
57 if ( $foundStart ) {
58 # Found match
59 $output .= call_user_func( $callback, array(
60 substr( $subject, $outputPos, $m[2][1] + strlen( $m[2][0] ) - $outputPos ),
61 substr( $subject, $contentPos, $m[2][1] - $contentPos )
62 ));
63 $foundStart = false;
64 } else {
65 # Non-matching end, write it out
66 $output .= substr( $subject, $inputPos, $m[2][1] + strlen( $m[2][0] ) - $outputPos );
67 }
68 $inputPos = $outputPos = $m[2][1] + strlen( $m[2][0] );
69 } else {
70 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
71 }
72 }
73 if ( $outputPos < strlen( $subject ) ) {
74 $output .= substr( $subject, $outputPos );
75 }
76 return $output;
77 }
78
79 /*
80 * Perform an operation equivalent to
81 *
82 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
83 *
84 * @param string $startDelim Start delimiter regular expression
85 * @param string $endDelim End delimiter regular expression
86 * @param string $replace Replacement string. May contain $1, which will be
87 * replaced by the text between the delimiters
88 * @param string $subject String to search
89 * @return string The string with the matches replaced
90 */
91 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
92 $replacer = new RegexlikeReplacer( $replace );
93 return self::delimiterReplaceCallback( $startDelim, $endDelim,
94 $replacer->cb(), $subject, $flags );
95 }
96
97 /**
98 * More or less "markup-safe" explode()
99 * Ignores any instances of the separator inside <...>
100 * @param string $separator
101 * @param string $text
102 * @return array
103 */
104 static function explodeMarkup( $separator, $text ) {
105 $placeholder = "\x00";
106
107 // Remove placeholder instances
108 $text = str_replace( $placeholder, '', $text );
109
110 // Replace instances of the separator inside HTML-like tags with the placeholder
111 $replacer = new DoubleReplacer( $separator, $placeholder );
112 $cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
113
114 // Explode, then put the replaced separators back in
115 $items = explode( $separator, $cleaned );
116 foreach( $items as $i => $str ) {
117 $items[$i] = str_replace( $placeholder, $separator, $str );
118 }
119
120 return $items;
121 }
122
123 /**
124 * Escape a string to make it suitable for inclusion in a preg_replace()
125 * replacement parameter.
126 *
127 * @param string $string
128 * @return string
129 */
130 static function escapeRegexReplacement( $string ) {
131 $string = str_replace( '\\', '\\\\', $string );
132 $string = str_replace( '$', '\\$', $string );
133 return $string;
134 }
135 }
136
137 /**
138 * Base class for "replacers", objects used in preg_replace_callback() and
139 * StringUtils::delimiterReplaceCallback()
140 */
141 class Replacer {
142 function cb() {
143 return array( &$this, 'replace' );
144 }
145 }
146
147 /**
148 * Class to replace regex matches with a string similar to that used in preg_replace()
149 */
150 class RegexlikeReplacer extends Replacer {
151 var $r;
152 function __construct( $r ) {
153 $this->r = $r;
154 }
155
156 function replace( $matches ) {
157 $pairs = array();
158 foreach ( $matches as $i => $match ) {
159 $pairs["\$$i"] = $match;
160 }
161 return strtr( $this->r, $pairs );
162 }
163
164 }
165
166 /**
167 * Class to perform secondary replacement within each replacement string
168 */
169 class DoubleReplacer extends Replacer {
170 function __construct( $from, $to, $index = 0 ) {
171 $this->from = $from;
172 $this->to = $to;
173 $this->index = $index;
174 }
175
176 function replace( $matches ) {
177 return str_replace( $this->from, $this->to, $matches[$this->index] );
178 }
179 }
180
181 /**
182 * Class to perform replacement based on a simple hashtable lookup
183 */
184 class HashtableReplacer extends Replacer {
185 var $table, $index;
186
187 function __construct( $table, $index = 0 ) {
188 $this->table = $table;
189 $this->index = $index;
190 }
191
192 function replace( $matches ) {
193 return $this->table[$matches[$this->index]];
194 }
195 }
196
197 /**
198 * Replacement array for FSS with fallback to strtr()
199 * Supports lazy initialisation of FSS resource
200 */
201 class ReplacementArray {
202 /*mostly private*/ var $data = false;
203 /*mostly private*/ var $fss = false;
204
205 /**
206 * Create an object with the specified replacement array
207 * The array should have the same form as the replacement array for strtr()
208 */
209 function __construct( $data = array() ) {
210 $this->data = $data;
211 }
212
213 function __sleep() {
214 return array( 'data' );
215 }
216
217 function __wakeup() {
218 $this->fss = false;
219 }
220
221 /**
222 * Set the whole replacement array at once
223 */
224 function setArray( $data ) {
225 $this->data = $data;
226 $this->fss = false;
227 }
228
229 function getArray() {
230 return $this->data;
231 }
232
233 /**
234 * Set an element of the replacement array
235 */
236 function setPair( $from, $to ) {
237 $this->data[$from] = $to;
238 $this->fss = false;
239 }
240
241 function mergeArray( $data ) {
242 $this->data = array_merge( $this->data, $data );
243 $this->fss = false;
244 }
245
246 function merge( $other ) {
247 $this->data = array_merge( $this->data, $other->data );
248 $this->fss = false;
249 }
250
251 function replace( $subject ) {
252 if ( function_exists( 'fss_prep_replace' ) ) {
253 if ( $this->fss === false ) {
254 $this->fss = fss_prep_replace( $this->data );
255 }
256 return fss_exec_replace( $this->fss, $subject );
257 } else {
258 return strtr( $subject, $this->data );
259 }
260 }
261 }
262
263 ?>