Sweet Regex thing…

Posted on October 2nd, 2007 by Tidwell.
Categories: Programming.

Most of you probably will have no idea what this is…but it its my first example of using regular expressions to do string parsing and feeding that back as a function call..its well documented – check it after the break

<?php
/*
Takes a string ($text) and replaces all regex matches with the return from a function call of the same name.
Usage:  run_replace_callback($regex, $text);
You can overload the defaults set below in the function call
	overloaded example: run_replace_callback('/:([a-zA-Z_]+)/', 'this is the text :functiontodo');
*/

//the regular expression used for parsing
$regex = '/:([a-zA-Z_]+)/';
//the preface tag to add to the string before calling the function
$func_preface = 'userfunction_';
//the string to be parsed
$text = "This is some text and do the following function :dofunction and more text";

//the functions that render the replacement text - note that all function names must start with the value of $func_preface
//Place all functions below -- if you have a lot, probably will want to put these in another included php file
function userfunction_dofunction() {
  return 'FUNCTION RESULT';
}
//END FUNCTIONS

//the function that takes the matched text, adds the preface, and runs the function if it exists.  Otherwise returns the full match
function run_user_function($matches) {
	global $func_preface;
	// as usual: $matches[0] is the complete match
	// $matches[1] the match for the first subpattern
	$function = $func_preface.$matches[1];
	if(function_exists($function)) {
		return call_user_func($function);
	}
}

//the function that accepts the regex to use and the text to use and runs the preg_replace_callback function
function run_replace_callback($regex_to_use, $text_to_use) {
	echo preg_replace_callback(
			$regex_to_use,
            'run_user_function',
            $text_to_use);
}
?>

no comments yet.

Leave a Comment

Names and email addresses are required (email addresses aren't displayed), url's are optional.

Comments may contain the following xhtml tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>




CAPTCHA image