2013-01-18 51 views
-1

我在我的bbcode中使用userid,但我想顯示用戶名! 所以我想要一個查詢做類似如何在SQL查詢中使用preg變量

SELECT username 
FROM users 
WHERE id = "$1"'; 

這怎麼可能?或者還有其他解決方案嗎? 我希望輸出是「約翰說」而不是「2說」。

<?php 
$str = "[quote=2]Foobar[/quote]"; 

$match = "/\[quote=(.*?)\](.*?)\[\/quote\]/is"; 
$replace = "<div class=\"quote\">$1 said:<br />>$2</div>"; 
$bbcode = preg_replace($match, $replace, $str); 
?> 
+0

爲什麼你不使用BBCode分析器? – Gordon

+0

喜歡什麼?我查了一下,但似乎無法找到任何看起來不錯的東西。 – user1989781

+0

像[native one?](http://php.net/manual/en/book.bbcode.php)。 – Gordon

回答

0

您需要preg_replace_callback修改替換/其插入到您的字符串之前,請用正確的用戶名的用戶ID。

0

您使用preg_replace_callback功能,

$bbcode = preg_replace_callback($match, function($matches){ 
     // execute query 
     $query = "SELECT username FROM users WHERE id = '{$matches[1]}'"; 
     // get user name 
     $username = $row['username']; // just for illustration. 
     // return formatted string. 
     return "<div class=\"quote\">$username said:<br />>$matches[2]</div>"; 
}, $str); 

哦,有一個更好的方式,這樣做。爲他們每個人運行SQL查詢不是一個好主意。因此,首先獲取所有用戶ID一個內容。然後從數據庫中獲取所有相應的名稱。

$match = "/\[quote=(.*?)\](.*?)\[\/quote\]/is"; 
preg_match_all($match, $str, $matches); 

$query = "SELECT id, username from tbl1 where id IN (".implode(",", $matches[1]).")"; 
// run the query. get all the row in a hash. 
$hash[$row['id']] = $hash[$row['username']]; 

$bbcode = preg_replace_callback($match, create_function(
    '$m', 
    'global $hash;return "<div class=\\"quote\\">{$hash[$m[1]]} said:<br />$m[2]</div>";' 
    ), $str); 
+0

我試過$ var ['\\ 1']和$ var ['$ 1'],但它似乎不起作用。 什麼是正確的語法? – user1989781

+0

@ user1989781更新。它現在會工作。我已經測試過它。 http://ideone.com/6qgD9w –