Suppose you’re an object-oriented person that prefers using classes. Below is the corresponding code using the OOP (object-oriented programming) approach: <?php $str = " list 1 <ol> <li>item A</li> <li>item B</li> <li>item C</li> </ol> list 2 <ol> <li>item D</li> <li>item E</li> <li>item F</li> <li>item G</li> </ol> list 3 <ol> <li>item H</li> <li>item I</li> <li>item J</li> <li>item K</li> <li>item L</li> </ol> "; $app = new ProcessList(); echo preg_replace_callback('%<ol>(.*?)</ol>%si', array(&$app, 'process_list'), $str); class ProcessList { function process_list($matches) { global $sno; $sno = 0; return preg_replace_callback("/<li>(.*?)</li>/i", array(&$this, 'process_item'), trim($matches[1])); } function process_item($matches) { global $sno; ++$sno; return "$sno. $matches[1]"; } } ?> Note the use of array(&$app, 'process_list') and array(&$this, 'process_item') in specifying the callback functions. The first parameter is the pointer to your object, and the second is the method name of the callback function in that object. Final Words We’ve come to the end of this article. In this tutorial, you have seen that the preg_replace_callback() function works exactly like the preg_replace() function. The only difference is that instead of specifying a replacement string, you specify a callback function. It is in the callback function that you can do many amazing things to produce your desired replacement string. I hope the examples in this article have also get you excited about using the preg_replace_callback() function!
blog comments powered by Disqus |
|
|
|
|
|
|
|