用PHP过滤字

时间:2017-02-01 17:16:19

标签: php forms function magento filter

我试图在我的Magento网站上创建一个文字过滤器,基本上我有一个带有textarea的表单和一个提交按钮,如下所示:

<form id="answer_form_<?php echo $id;?>" class="form" method="post" 
action="<?php echo Mage::getUrl('productquestions/productquestions/saveanswers',array('product_questions_id'=>$id));?>">

<textarea id="txt_send" class="input-text required-entry " name="content" 
id="answer_content_<?php echo $id;?>" title="Content"></textarea>

<button id="btn_send" style="float: left;" type="submit" class="button" 
title="Send Message"><span><span><?php echo $this->__('Send Message') ?></span></span></button>

</form>

我需要做的是在表单提交之前保存在数据库中时过滤textarea中的单词,因此我创建了一些php函数并对其进行了调整。最终的代码是:

function wordFilter($text) {       
   $filter_terms = array('\bass(es|holes?)?\b','\bshit(e|ted|ting|ty|head)\b');
   $filtered_text = $text;

   foreach($filter_terms as $word) {
      $match_count = preg_match_all('/' . $word . '/i', $text, $matches);

      for($i = 0; $i < $match_count; $i++) {
         $bwstr = trim($matches[0][$i]);
         $filtered_text = preg_replace('/\b' . $bwstr . '\b/', str_repeat("*", strlen($bwstr)), $filtered_text);
     }

   }
   return $filtered_text;
}

if(isset($_POST['btn_send'])) {
   $text = htmlentities($_POST['txt_send']);

   $text = wordFilter($text);
}

到目前为止,我刚刚添加了两个单词进行测试,当我用两个单词做文本时,它会正常保存,而不会将它们更改为&#34; *****&#34;。我避免使用JS,因为它是客户端。

有人可以告诉我我错过了什么吗?

谢谢!

编辑:

作为Magento插件。该操作将表单重定向到: productquestions/productquestions/saveanswers',array('product_questions_id'=>$id));并根据ID更改网址。例如:siteurl/index.php/productquestions/productquestions/saveanswers/product_questions_id/40 在这个控制器页面中,我有以下功能:

public function saveanswersAction() 
    {
        $answers = $this->getRequest()->getPost();
        $answerCollection = array();
        $model = Mage::getModel('productquestions/answers'); 
        $id = $this->getRequest()->getParam('product_questions_id');

        $model->setData('product_questions_id',$id);
        $model->setData('answers',$answers['content']);

        $model->save();
        $answerCollection[] = $model;

    }

2 个答案:

答案 0 :(得分:2)

有点难以确定,因为您没有包含执行保存的代码,但看起来您没有将过滤器函数的结果保存回保存的变量中。 尝试:

if(isset($_POST['btn_send'])) {
    $text = htmlentities($_POST['txt_send']);
    $text = wordFilter($text);
    //Code to save $text here
}

答案 1 :(得分:0)

只需将代码移动到控制器即可,感谢提示。

$text = $this->getRequest()->getParam('content');
        $filter_terms = array('\bass(es|holes?)?\b','\bshit(e|ted|ting|ty|head)\b');
        $filtered_text = $text;
        foreach($filter_terms as $word)
        {
             $match_count = preg_match_all('/' . $word . '/i', $text, $matches);
             for($i = 0; $i < $match_count; $i++)
             {
                   $bwstr = trim($matches[0][$i]);
                   $filtered_text = preg_replace('/\b' . $bwstr . '\b/', str_repeat("*", strlen($bwstr)), $filtered_text);
             }
        }

$model->setData('answers',$filtered_text);