使用“function(array $ matches)”时出现意外的T_FUNCTION错误

时间:2010-09-07 09:19:44

标签: php syntax-error

您好我正在使用以下代码,但我第二行遇到“意外的T_FUNCTION”语法错误。有什么建议吗?

preg_replace_callback("/\\[LINK\=(.*?)\\\](.*?)\\[\/LINK\\]/is",
function (array $matches) {
    if (filter_var($matches[1], FILTER_VALIDATE_URL))
        return '<a href="'.
            htmlspecialchars($matches[1], ENT_QUOTES).
            '" target="_blank">'.
            htmlspecialchars($matches[2])."</a>";
    else
        return "INVALID MARKUP";
}, $text);

1 个答案:

答案 0 :(得分:21)

当您的PHP超过5.3时会发生这种情况。匿名函数支持直到5.3才可用,因此PHP不会识别作为参数传递的函数签名。

您必须以传统方式创建一个函数,并改为传递其名称(例如,我使用link_code()):

function link_code(array $matches) {
    if (filter_var($matches[1], FILTER_VALIDATE_URL))
        return '<a href="'.
            htmlspecialchars($matches[1], ENT_QUOTES).
            '" target="_blank">'.
            htmlspecialchars($matches[2])."</a>";
    else
        return "INVALID MARKUP";
}

preg_replace_callback("/\\[LINK\=(.*?)\\\](.*?)\\[\/LINK\\]/is", 'link_code', $text);

此外,array $matches不是问题,因为PHP 5.2支持数组的类型提示。