The Function:
function doSomething($url){
$url = "<a href=\"{$url}\" target=\"blank\" title=\"{$url}\">{$url}</a>";
return $url;
}
The replacement
$content = preg_replace("#(http:\/\/+[^\s]+)#ie","doSomething('$1')", $content);
The Problem:
Fatal error: Cannot redeclare
doSomething() (previously declared
in
http://example.com/test.php:69)
in http://example.com/test.php
on line 69
Note: The current function does not represent my real function, I know that for this situation I don’t need any functions but in my real code I need. But this is a better example also.
Well, it’s because the function was already defined in a prior function call (That’s the danger in declaring a function inside of another function). There are a few options.
Conditionally declaring the function
Declaring an anonymous function:
PHP 5.3+ :
PHP 5.2+ :
Using a class:
Also, I’d suggest not using the
emodifier for the regex (it’s just not necessary, and it’s basically justeval, which is typically seen as evil). You should instead just usepreg_replace_callback:Assuming
$callbackis a valid callback: