Alternative for my preg_replace code
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 m开发者_运维知识库y code above because it was simple but I may have to use more complex code...
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.
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.
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.
foreach ($pageurl AS $num => $url) {
$search[] = "/page-({$num})-/sie";
$replace[] = $url;
}
$content_text = preg_replace($search, $replace, $content_text);
精彩评论