2012-03-23 82 views
0

當用戶輸入完整的url ..我想只保存youtube id ... pregmatch檢查並提取視頻ID,然後它將被保存到數據庫..問題是如何使這項pregmatch檢查,並提取YouTube的ID之前保存的完整URL 感謝幫助如何匹配輸入字段,然後將其保存在cakephp

//這是添加()函數videos_controller

function add() { 
     if (!empty($this->data)) { 

      $this->Video->create(); 

      if ($this->Video->save($this->data)) { 
       $this->Session->setFlash(__('The Video has been saved', true)); 
       $this->redirect(array('action' => 'admin_index')); 
      } else { 
       $this->Session->setFlash(__('The Video could not be saved. Please, try again.', true)); 
      } 
     } 
     $vcats = $this->Video->Vcat->find('list'); 
     $this->set(compact('vcats')); 
    } 

//這是add.ctp文件

<div class="videos form"> 
    <?php // echo $this->Form->create('Image');?> 
    <?php echo $form->create('Video'); ?> 
    <fieldset> 
     <legend><?php __('Add Video'); ?></legend> 
     <?php 
     echo $this->Form->input('vcat_id'); 
     echo $this->Form->input('title'); 
     $url= $this->Form->input('link'); 
     echo $url 
     ?> 
    </fieldset> 
    <?php echo $this->Form->end(__('Submit', true)); ?> 
</div> 
<div class="actions"> 
    <h3><?php __('Actions'); ?></h3> 
    <ul> 

     <li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li> 
     <li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li> 
     <li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li> 
    </ul> 
</div> 

//我們通過匹配模式獲取URL中的獨特的視頻ID,但在這裏我把這個代碼以匹配之前保存

preg_match("/v=([^&]+)/i", $url, $matches); 
$id = $matches[1]; 

回答

1

這裏

function add() { 
    if (!empty($this->data)) { 

     $this->Video->create(); 
     $url = $this->data['Video']['link']; 

     /*assuming you have a column `id` in your `videos` table 
     where you want to store the id, 
     replace this if you have different column for this*/ 

     preg_match("/v=([^&]+)/i", $url, $matches); 
     $this->data['Video']['id'] = $matches[1]; 

     //rest of the code 
    } 
} 
0

我想一個更好的地方,因爲這是在型號的beforeSavebeforeValidate方法:

class Video extends AppModel { 

    ... 

    public function beforeSave() { 
     if (!empty($this->data[$this->alias]['link'])) { 
     if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) { 
      $this->data[$this->alias]['some_id_field'] = $matches[1]; 
     } 
     } 
     return true; 
    } 

    ... 

} 
相關問題