Alertnative for my preg_replace code

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Alertnative for my preg_replace code

Post 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...
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Alertnative for my preg_replace code

Post 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.
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Re: Alertnative for my preg_replace code

Post 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);
Post Reply