简体   繁体   English

将变量从foreach循环传递给php

[英]Passing a variable from foreach loop to php

I am lost with a problem I am working on. 我迷上了正在解决的问题。

I have a HTML form with a few radio buttons and a submit button. 我有一个带有几个单选按钮和一个提交按钮的HTML表单。 From this form, the user will be able to select one of the radio buttons, and then click submit. 通过此表单,用户将能够选择单选按钮之一,然后单击“提交”。 This will start the PHP script and the script should pull out words from a string that do not match the number that was selected from the radio button. 这将启动PHP脚本,并且该脚本应从与单选按钮选择的数字不匹配的字符串中提取单词。

Whereas I am comfortable with HTML, PHP is giving me a little more trouble. 我对HTML感到满意,但是PHP给我带来了更多麻烦。

Here is where I am stuck: 这是我被困的地方:

    $myTok = strtok($fileContents, "\"!@#$%^&*(1234567890).,:;'_?\n\t-[]~{}");

while ($myTok != false){

    $myTok = strtok( "\"!@#$%^&*(1234567890).,:;'_?\n\t-[]~{}");

        foreach ($myTok as $key => $value){
            if (strlen($value == 1)){
                                   //not sure how to return the value to the $resultWords variable here

}
}

$resultWords = 

I have a string (ex. "I am having a hard time with the PHP script.") I am using the strtok() function remove any delimiters that are not needed and that would count as an extra character to the $value in my foreach loop but I am wanting ONLY the words. 我有一个字符串(例如,“我在使用PHP脚本时遇到麻烦。”)我正在使用strtok()函数删除不需要的任何定界符,这些定界符将作为$ value的额外字符foreach循环,但我只想要单词。

So with the foreach loop, I am going through every token value to see if the word matches the length that the user chose. 因此,通过foreach循环,我将遍历每个标记值,以查看单词是否与用户选择的长度匹配。 These are the words that I want to remove from the string. 这些是我想从字符串中删除的单词。 So, my new string would look like "I am having a the PHP script" if the user chose radio button 4. I want to do this using a foreach() loop. 因此,如果用户选择了单选按钮4,那么我的新字符串将看起来像“我正在使用PHP脚本”。我想使用foreach()循环来完成此操作。 My biggest confusion is how to return the modified string from the loop back out to the variable $resultWords or if I even have the beginning of my foreach loop setup correctly. 我最大的困惑是如何将修改后的字符串从循环中返回到变量$ resultWords,或者甚至我是否正确地开始了foreach循环设置。

Would it be recommended to use the explode() function to make it all an array before the foreach loop? 建议在foreach循环之前使用explode()函数将其全部设置为数组吗? Sorry, I am a bit newbish with this. 抱歉,我对此有点不满意。

You can modify your script in the below way. 您可以通过以下方式修改脚本。

$resultWords  = array();
foreach ($myTok as $key => $value){

 if (strlen($value == 1)){

        $resultWords[] = $value;                   

    }
}

//Make use of the array now. 
foreach($resultWords as $key => $value) {

    //$value will contain the words

}

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

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