简体   繁体   English

如何从函数返回变量?

[英]How do I return the variable from a function?

I am trying to return a variable from a function and print it out. 我正在尝试从函数返回变量并将其打印出来。 Its displaying unexpected T_STRING right now.... Can someone help? 它现在显示出意外的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);
function reg_word($i){
    $reg_word = "/[^A-Za-z0-9 ]/";
    return preg_replace($reg_word, '', $i);
}

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

print_r($suggestion);

You had function keyword before reg_word($_POST['suggestions']); 您在reg_word($_POST['suggestions']);之前有function关键字reg_word($_POST['suggestions']); - you don't need it. -您不需要。 You need to use return keyword to return something from a function. 您需要使用return关键字从函数中返回某些内容。

You've got one function keyword wrong, try: 您有一个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);

Wrong function keyword, you do NOT return any value in function. 错误的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM