tags:

views:

88

answers:

4

Here is my code... basically it finds any page-NUMBER- within a variable and then replaces it with a page url from an array

$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...

A: 

Add a check into the replacement to see if the item exists in the array or not. Might be easier to read if you put the code into a function and used preg_replace_callback instead of the e flag.

Matti Virkkunen
+1  A: 

Syntax might not be 100% correct but;

$content_text = preg_replace_callback('/page-(\d+)-/sie',
    create_function('$number',
                    'global $pageurl;
                    if (in_array($number, $pageurl)){
                        return $pageurl[$number];
                    }else{
                        /*do something*/
                    };'),
    $content_text);

EDIT Forgot to include "global $pageurl;" to be able to access the variable inside the function.

bigstylee
Imagine how much better this would look with an anonymous function. I know that support isn't until 5.3, but it will be a good day.
alex
Yep perfect! I just had to remove the e flag from your code. Also the global didn't work so I had to put the $pageurl within the function. in-array() didn't work either so I just ussed isset($pageurl[$number[1])). Thanks for your help!
Ben Sinclair
A: 

Why don't you get the numbers with preg_match_all, create a replacement array based on the numbers you got, and then run a str_replace with those arrays. That way you can assure a 1-1 replacement.

Ben
A: 
foreach ($pageurl AS $num => $url) {
    $search[] = "/page-({$num})-/sie";
    $replace[] = $url;
}
$content_text = preg_replace($search, $replace, $content_text);
TiuTalk