我會做這樣:
$images = array();
$post = preg_replace_callback('|\[img\](\d+)\[/img\]|i', function($matches) use(&$images) {
$images[] = $matches[1];
return '__image_' . $matches[1];
}, $post);
if (count($images)) {
// Select images
$imageIds = implode(',', $images);
// DB query
$res = mysql_query("SELECT id, path FROM post_images WHERE id IN ({$imageIds})") or die(mysql_error());
// Replace
while (($row = mysql_fetch_assoc($res))) {
$post = str_replace('__image_'.$row['id'], '<img src=' . $row['path'] . ' />', $post);
}
}
的好處是,你做只有一個查詢數據庫。將它們最小化以提高性能始終是非常重要的。如果你不小心,或者你確信不會圖像的數量太高,你可以簡單的使用這個代碼:
$post = preg_replace_callback('|\[img\](\d+)\[/img\]|i', function($matches) {
$res = mysql_query("SELECT path FROM post_images WHERE id = {$matches[1]}") or die(mysql_error());
$path = mysql_result($res, 0);
return "<img src='$path' />";
}, $post);
您可以發佈您到目前爲止嘗試過的嗎?這感覺就像你試圖得到一個完整的解決方案,那不是什麼StackOverflow是關於:) –
不是一個真正的完整的解決方案,只是關鍵的想法;) –