2012-08-16 52 views
1

我需要一種智能的方式讓用戶在課程中發佈來自Forvo的語音片段。 Forvo需要使用$ this-> Forvo-> word('hola','es')來使用幫助器。如何動態替換bb標籤?

一個想法是允許用戶使用像[forvo = hola,es]這樣的bb-code,但是如何實現呢?我唯一能想到的就是使用很多substr,strpos ......這將需要至少35行代碼,這不會很漂亮和安全。一節課的

<?php 
// Replace forvos in the lesson 
$lesson = $lesson['Lesson']['body']; 

// Todo: 
// Replace [forvo=hello,en] by javascript from 
// $this->Forvo->word('hello', 'en'); 

// I seem unable to use regex's like this 
$pattern[0] = "/\[forvo\=(.*),(.*)]"; 
$replace[0] = $this->Forvo->word($1, $2); 
echo preg_replace($pattern, $replace, $lesson); 

?> 

例子是:

Pronounciations in Dutch 
    een [forvo=een,nl] 
    en [forvo=en,nl] 
    de [forvo=de,nl] 
    in [forvo=in,nl] 
    met [forvo=met,nl] 
+1

試試看preg_replace_callback()http://php.net/manual/en/function.preg-replace-callback.php – Waygood 2012-08-16 13:56:25

回答

0

謝謝你,Waygood。它適用於preg_replace_callback。

<?php 
// Replace forvos in the lesson 
$lesson = $lesson['Lesson']['body']; 

function forvize($match) { 
    $word = $match[1]; 
    $language = $match[2]; 
    $link = "http://apifree.forvo.com/action/word-pronunciations/format/js-tag /word/".$word."/language/".$language."/order/rate-desc/limit/1/key/123456789/"; 
    $link = file_get_contents($link); 
    return $link; 
} 

//URL's 
$lesson = preg_replace_callback("/\[forvo\=(.*),(.*)\]/", 'forvize', $lesson); 
?>