Page 1 of 1

Alertnative for my preg_replace code

Posted: Wed Mar 31, 2010 7:13 pm
by Mr Tech
Here is my code... basically it finds any page-NUMBER- within a variable and then replaces it with a page url from an array

Code: Select all

$content_text = preg_replace("/page-(\d+)-/sie", '$pageurl[$1]', $content_text);
It works a treat until the NUMBER it finds isn't in the array and it returns an error...

Is there another efficient way I could do this instead?

I liked my code above because it was simple but I may have to use more complex code...

Re: Alertnative for my preg_replace code

Posted: Fri Apr 02, 2010 3:44 pm
by tr0gd0rr
Instead of using the `e` flag, you can use preg_replace_callback. In the callback, return the original string if the number is not in the array.

Re: Alertnative for my preg_replace code

Posted: Mon Apr 05, 2010 8:32 pm
by Mr Tech
Awesome! This is what my coded ended up being:

Code: Select all

$content_text = preg_replace_callback('/page-(\d+)-/si',
		create_function('$number',
			'$pageurls = load_pageurls();
			  if (isset($pageurls[$number[1]])) {
				return $pageurls[$number[1]];
			} else {
				return '';
			};'),
		$content_text);