如何从函数返回变量?

时间:2012-07-07 07:44:51

标签: php function

我试图从函数返回一个变量并将其打印出来。它现在显示意外的T_STRING ....有人可以帮忙吗?

function reg_word($i){
        $reg_word = "/[^A-Za-z0-9 ]/";
        $i = preg_replace($reg_word, '', $i);
    }

$suggestion = function reg_word($_POST['suggestions']);

    print_r($suggestion);

3 个答案:

答案 0 :(得分:0)

function reg_word($i){
    $reg_word = "/[^A-Za-z0-9 ]/";
    return preg_replace($reg_word, '', $i);
}

$suggestion = reg_word($_POST['suggestions']);

print_r($suggestion);

function之前您有reg_word($_POST['suggestions']);个关键字 - 您不需要它。 您需要使用return关键字从函数中返回一些内容。

答案 1 :(得分:0)

您有一个function个关键字错误,请尝试:

function reg_word($i){
        $reg_word = "/[^A-Za-z0-9 ]/";
        $i = preg_replace($reg_word, '', $i);
    }

$suggestion = reg_word($_POST['suggestions']);

    print_r($suggestion);

答案 2 :(得分:0)

错误的function关键字,您不会在函数中返回任何值。

function reg_word($i){
        $reg_word = "/[^A-Za-z0-9 ]/";
        return preg_replace($reg_word, '', $i); // return added
    }

$suggestion = reg_word($_POST['suggestions']); // here function was

    print_r($suggestion);