2011-02-08 87 views
1

我想創建一個簡化的代碼,根據類似於BBCode的用戶輸入動態地將圖像插入頁面。例如,如果我的一個用戶鍵入「我喜歡鴨子[圖像]鴨子[/圖像]」,我想炸開[圖像]鴨子[/圖像],在關鍵詞「鴨子」中搜索MySQL,從匹配的數據庫中拉出圖像路徑&名稱,然後顯示圖像HTML代碼以及圖像的源代碼。用圖像替換動態文本

function image_replace($dimg){ 
    list($title) = explode("[image]",$dimg); 
    $query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$title%'"); 
    $fetch_image = mysql_fetch_array($query_image); 
    $image_path = $fetch_image['image_path']; 
    $image_filename = $fetch_image['image_filename']; 
    $image_source = $image_path.$image_filename; 
    $dimg = str_replace("[image]","<img src=\"$image_source\">", $dimg); 
    $dimg = str_replace("[/image]","</img>", $dimg); 
    $dimg = str_replace("$title", "", $dimg); 
    return $img; 
    } 

image_replace($ducks); 

我撞牆是如何,如果它存在代替動態生成的頁面中的文本 - 和先不談內容如果代碼不存在。有任何想法嗎?


編輯 - 更爲複雜的問題:

感謝您的幫助!我用了你的輸入作出如下功能:

function image_replace($string){ 
    $matches = array(); 
    preg_match('/\[image\](.*)\[\/image\]/', $string, $matches); 
    $image = $matches[1]; 
    $query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$image%'"); 
    $fetch_image = mysql_fetch_array($query_image); 
    $image_path = $fetch_image['image_path']; 
    $image_filename = $fetch_image['image_filename']; 
    $image_source = $image_path.$image_filename; 
    $image_url = "<img src=\"$image_source\"></img>"; 
    $new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string); 

    return $new_string; 
    } 

我需要不管這個工作的有多少實例發生(因此,如果我的用戶寫道圖像]鴨[/圖片],然後兩句話後來寫道圖像] cow [/ image],我希望函數能夠用它們各自的結果替換它們)。就目前而言,由於preg_match只查找一個實例,因此它有多個錯誤(不是有效的SQL資源),這是合理的。我試圖創建一個循環(而&的foreach W/preg_match_all)嘗試測試的概念 - 無論是創建無限循環和我的Web服務器管理員很不是滋味:對

+0

考慮新的問題。我會修補一下。 – 2011-02-09 15:37:09

+0

Alrighty我的男人,看看我的答案編輯,讓我知道如果這是訣竅! – 2011-02-09 15:49:50

回答

1

我會嘗試用preg_match做它來獲得IMAGE_URL和preg_replace來代替它:

$string = 'I like ducks [image]ducks[/image]'; 
echo 'Before: ' . $string . '<br />'; 
$matches = array(); 
preg_match('/\[image\](.*)\[\/image\]/', $string, $matches); 
$image = $matches[1]; 
//Lookup image_url and throw it in an <img> 
$image_url = 'http://blah.com'; //Don't forget <img> 
$new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string); 
echo 'After: ' . $new_string; 

編輯

$string = "<br />I like ducks [image]ducks[/image]<br />I like cows [image]cows[/image]<br />I like pigs [image]pigs[/image]"; 
echo 'Before: ' . $string . '<br />'; 

$matches = array(); 
preg_match_all('/\[image\]([^\[]*)\[\/image\]/', $string, $matches); 
$image_names = $matches[1]; 
foreach($image_names as $image_name) { 
    //Perform your lookup on each name 
    //If it is valid perform the replace 
    //Gonna say cows isn't there to test 
    if($image_name != 'cows') { 
     $image_url = 'http://blah.com'; //result of lookup 
     $string = preg_replace('/\[image\]' . $image_name . '\[\/image\]/', $image_url, $string); 
    } 
} 
echo 'After: ' . $string;