php - 将textarea中的单独单词放入变量中

时间:2016-06-08 16:55:30

标签: php html

我需要扫描tetxarea输入文本以查找标记的单词并将它们放在变量中。

 <textarea type="text" class="form-control" id="text" placeholder="put some text" name="text"></textarea>

例如,textarea中的文本是

 Every [day] I go to the [shop].

当表单被POST时,括号中的单词必须在变量中传递,这些变量是自动生成的,它必须是那样的

 $word1 = "day";
 $word2 = "shop";

2 个答案:

答案 0 :(得分:3)

您可以使用preg_match_all,例如

preg_match_all ( "/\[([^\]]+)\]/ism", $textarea, $matches );

$匹配将是:

Array
(
    [0] => Array
        (
            [0] => [day]
            [1] => [shop]
        )

    [1] => Array
        (
            [0] => day
            [1] => shop
        )

)

和$ matches [1]将包含一个包含您单词的数组。

答案 1 :(得分:1)

嗯,你可以尝试这样的事情:

    <?php
        $textAreaText = $_POST["text"]; 
        preg_match("#(\[.*\])#si", $textAreaText, $matches); //<== MATCH EVERY TEXT WITHIN []

        // THE MATCHES ARRAY CONTAINS ANY TEXT ENCLOSED WITHIN []
        var_dump($matches); 

        // HOWEVER, YOU MAY HAVE TO ACCESS THE VARIABLES USING NUMBERS LIKE:
        // $matches[1]... etc
        // OR YOU COULD USE A LOOP AND CREATE VARIABLES OUT OF THE $matches ARRAY LIKE SO:
        $arrWords     = array();

        foreach($matches as $iKey=>$match){
            if($iKey != 0){
                $key            = "word" . $iKey;
                $arrWords[$key] = $match;
            }
        }

        // EXTRACT THE DATA IN THE ARRAY INTO VARIABLES:
        extract($arrWords);

        // NOW YOU COULD DO SOMETHING LIKE 
        echo $word1; // ASSUMING YOU HAVE AT LEAST 1 WORD WRAPPED WITHIN []
        echo $word2; // ASSUMING YOU HAVE UP TO 2 WORDS WRAPPED WITHIN []
        echo $word3; // ASSUMING YOU HAVE UP TO 3 WORDS WRAPPED WITHIN []