PHP: Using preg_replace_callback in an OOP environment

As I was using the preg_replace_callback function today I realized I had no idea how to use it in an OOP environment. I deviced the following example to show how to use the function inside a class where the callback is in fact a function in the class:

<?php 
 
class TestClass
{
	private function testCallback($text)
	{
		$age = $text[0];
		$age++;
		return $age;
	}
 
	public function parse($text)
	{
		return preg_replace_callback(
			"([0-9]+)", 
			array($this, 'testCallback'), 
			$text);
	}
}
 
$testClass = new TestClass();
$text = "My name is XXX and I'm 78 years old!";
 
$newText = $testClass->parse($text);
 
echo "Old text: $text<br />";
echo "New text: $newText<br />";
 
?>

This would output:

Old text: My name is XXX and I'm 78 years old!
New text: My name is XXX and I'm 79 years old!
Posted in PHP

Leave a Reply