Php Yii:将字符串中的每个单词大写,并将其传递给数据库

Php Yii:将字符串中的每个单词大写,并将其传递给数据库,php,yii,yii-cactiverecord,Php,Yii,Yii Cactiverecord,我想把字符串中的每个单词大写 例如:“汽车和自行车” 到“汽车和自行车” 在不大写“and”、“or”、“of”等的情况下,然后我想将修改后的字符串发送到数据库。请告诉我如何在Yii 1.1框架中做到这一点 我的模型看起来像这样 <?php /** * This is the model class for table "master". * * The followings are the available columns in table 'master': * @prop

我想把字符串中的每个单词大写

例如:
“汽车和自行车”

“汽车和自行车”

在不大写“and”、“or”、“of”等的情况下,然后我想将修改后的字符串发送到数据库。请告诉我如何在Yii 1.1框架中做到这一点

我的模型看起来像这样

<?php

/**
 * This is the model class for table "master".
 *
 * The followings are the available columns in table 'master':
 * @property integer $book_id
 * @property string $book_name
 * @property string $book_author
 * @property string $book_category
 * @property string $book_publisher
 * @property string $book_pyear
 * @property string $book_location
 * @property string $book_pages
 * @property integer $book_cost
 */
class Books extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'master';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('book_name, book_author, book_category, book_publisher, book_pyear, book_location, book_pages, book_cost', 'required'),
            array('book_cost', 'numerical', 'integerOnly'=>true),
            array('book_name', 'length', 'max'=>50,'min'=>5),
            array('book_author, book_category', 'length', 'max'=>20, 'min'=>3),
            array('book_publisher', 'length', 'max'=>40,'min'=>8),
            array('book_pyear', 'length', 'max'=>4),
            array('book_location', 'length', 'max'=>6),
            array('book_pages', 'length', 'max'=>8),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('book_id, book_name, book_author, book_category, book_publisher, book_pyear, book_location, book_pages, book_cost', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'book_id' => 'ID',
            'book_name' => 'Name',
            'book_author' => 'Author',
            'book_category' => 'Category',
            'book_publisher' => 'Publisher',
            'book_pyear' => 'Published Year',
            'book_location' => 'Location',
            'book_pages' => 'Pages',
            'book_cost' => 'Cost',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('book_id',$this->book_id);
        $criteria->compare('book_name',$this->book_name,true);
        $criteria->compare('book_author',$this->book_author,true);
        $criteria->compare('book_category',$this->book_category,true);
        $criteria->compare('book_publisher',$this->book_publisher,true);
        $criteria->compare('book_pyear',$this->book_pyear,true);
        $criteria->compare('book_location',$this->book_location,true);
        $criteria->compare('book_pages',$this->book_pages,true);
        $criteria->compare('book_cost',$this->book_cost);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Books the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}
<?php

class BooksController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Books;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Books'])) {
            $model->attributes=$_POST['Books'];
            if ($model->save()) {
                $this->redirect(array('view','id'=>$model->book_id));
            }
        }

        $this->render('create',array(
            'model'=>$model,
        ));

    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Books'])) {
            $model->attributes=$_POST['Books'];
            if ($model->save()) {
                $this->redirect(array('view','id'=>$model->book_id));
            }
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        } else {
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Books');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new Books('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Books'])) {
            $model->attributes=$_GET['Books'];
        }

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Books the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=Books::model()->findByPk($id);
        if ($model===null) {
            throw new CHttpException(404,'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Books $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax']==='books-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

如果您可以列出所有不需要更改的单词,那么我相信最简单的方法是:

  • 引爆绳子
  • 如果不在“禁止”列表中,请首先选择所有单词
  • 把它炸回去

  • 在控制器中添加以下方法

            function doCapitalize($string)
            {
                $exclude = array('and','is','or');
                $words = explode(' ', $string);
                foreach ($words as $key => $word)
                {
                    if (in_array($word, $exclude))
                    {
                        continue;
                    }
                    $words[$key] = ucfirst($word);
                }
                $newString = implode(' ', $words);
                return $newString;
            }
    
    现在,在将值分配给
    模型属性之前,对
    $\u POST
    值操作此方法

    我正在编写一个样本剪来创建一本书

            $createBook=array();
            foreach($_POST['Book'] as $key=>$val)
            {
                $createBook[$key]=$this->doCapitalize($val);
            }
    
    将此新createBook数组指定给模型属性

            $model->attributes =$createBook;
    

    值得一提的是:
    beforeSave()
    方法是一个很好的地方。感谢您及时的回复。但是如果你能把你的代码和我上面的控制器代码合并。我会很高兴的。@sush你应该可以自己做。删除
    $model->attributes=$\u POST['Books'if($key=='book_name'| |$key=='book_author'){$createBook[$key]=$this->doCapitalize($val);}或者{$createBook[$key]=$val;}
            $model->attributes =$createBook;