Extension:MultiReplace/Code
From MediaWiki.org
<?php /* MultiReplace extension for MediaWiki Copyright (C) 2009 Matěj Grabovský http://www.mediawiki.org/wiki/User:DJ_Jeri This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ $wgExtensionCredits['parserhook'][] = array( 'name' => 'MultiReplace', 'version' => '0.1 (2009-03-17)', 'description' => 'Enhances parser with ability to perform multiple regex and/or plain string replace function on given string', # 'descriptionmsg' => 'multireplace-desc', 'author' => 'Matěj Grabovský', 'url' => 'http://www.mediawiki.org/wiki/Extension:MultiReplace', ); $wgExtensionFunctions[] = 'wfMultiReplace'; $wgHooks['LanguageGetMagic'][] = 'wfMultiReplace_LanguageGetMagic'; function wfMultiReplace() { global $wgParser; $wgParser->setFunctionHook( 'multireplace', 'efMultiReplace_Render' ); } function wfMultiReplace_LanguageGetMagic( &$magicWords, $langCode = "en" ) { switch( $langCode ) { default: $magicWords['multireplace'] = array( 0, 'multireplace' ); } return true; } function efMultiReplace_Render( &$parser /*,...*/ ) { $args = func_get_args(); array_shift( $args ); $string = $args[0]; array_shift( $args ); $exprs = array(); foreach( $args as $expr ) { $tmp = array(); $tmp = explode( "=", $expr, 2 ); array_map( "trim", $tmp ); // Will maybe have to be removed $exprs[] = $tmp; // Alternative; would cause: // foo=bar=baz => Array( "foo=bar", "baz" ) // compared to the previous: // foo=bar=baz => Aray( "foo" , "bar" ) /* $tmp = array(); preg_match( "/(.*?)=([^=]*)/", $expr, &$tmp ); array_shift( $tmp ); $exprs[] = $tmp;*/ } $output = $string; foreach( $exprs as $replSet ) { $delim = "\\" . $replSet[0][0]; // Right name should be: Potentional delimiter // To be a regex the string must: if( // Be longer than 1 character (x can't be regex) strlen( $replSet[0] ) > 1 && // Perl regex delimiter can't be alphabetical (the previous test would let xz go through as regex) !ctype_alpha( $replSet[0][0] ) && // Must has the same character (delimiter) on beginning and simultaneously on the end of the string // + optional pattern modifiers) preg_match( "/^{$delim}{1}[^{$delim}]+{$delim}{1}[imsxeADSUXJu]*$/", $replSet[0] ) ) { // Regex => preg_replace() $output = preg_replace( $replSet[0], $replSet[1], $output ); } else { // Plain string => str_replace() $output = str_replace( $replSet[0], $replSet[1], $output ); } } return $output; }
