开发者

PHP : Function in preg_replace says that the function was already declared

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

if (!function_exists('doSomething')) {
    function doSomething($url)...
}

Declaring an anonymous function:

PHP 5.3+ :

$callback = function($url) {
    //...
}

PHP 5.2+ :

$callback = create_function('$url', '//...');

Using a class:

class foo {
    public function doReplace($string) {
        $callback = array($this, 'doSomething');
        // Do your matching here
    }
    public function doSomething($url) {
        //...
    }
}

Also, I'd suggest not using the e modifier for the regex (it's just not necessary, and it's basically just eval, which is typically seen as evil). You should instead just use preg_replace_callback:

Assuming $callback is a valid callback:

$callback = function($match) {
    $url = $match[1];
    //... Do stuff here
}
$string = preg_replace_callback($regex, $callback, $string);


As they say, doSomething has already been defined. Use doSomething2 :)


Well... error message says the problem. You have a declaration for doSomething() function several times.

Check out line 69 of test.php and try to comment declaration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜