的discuz! X 3.0 bbcode并附加preg_replace

时间:2013-05-22 12:45:50

标签: php javascript

$tid = $_GET['tid'];
require_once $_SERVER['DOCUMENT_ROOT'] . '/common/class/class.thread.php';
$thread = new getThread;
$getThread = $thread->get_content($tid);
require_once $_SERVER['DOCUMENT_ROOT'] . '/common/class/class.thread.php';
$thread = new getThread;
$getThread = $thread->get_content($tid);
$attachmentTable = substr($tid, -1);
$tdatabase = new threadDatabase();
$tdatabase->query('SELECT * FROM mycms_forum_attachment_' . $attachmentTable .  ' WHERE tid = :tid ORDER BY aid DESC');
$tdatabase->bind(':tid', $tid);
$attachmentContainer = $tdatabase->resultset();
print_r($attachmentContainer);

//following is content , it pull from db($getThread)
//main content start
[attach]42[/attach]


[align=left][attach]53[/attach][/align]
content bla bla bla                      content bla bla bla
[align=left][attach]52[/attach][/align]
content bla bla bla


content bla bla bla
//main content end

//following is attachment file
[0] => Array ( [aid] => 53 [tid] => 32 [pid] => 32 [uid] => 1 [filesize] => 152633 [attachment] => 201305/22/142619h42az34077hhra0p.jpg [width] => 1080 ) 
[1] => Array ( [aid] => 52 [tid] => 32 [pid] => 32 [uid] => 1 [filesize] => 89015 [attachment] => 201305/22/142618wx3njhgf3n883zxr.jpg [width] => 1080 ) 

如何使用preg_replace将[attach] 53 [/ attach]更改为

src取自于援助= 53的数组,因为它[attach] 53 [/ attach]和宽度

我试过以下,但得到错误,我知道这样做是错误的,因为$ attachmentContainer [$ 1] ['attachment']从0开始,53不存在,被困住,不知道做。

$threadContainer = preg_replace('/\[attach\](.*?)\[\/attach\]/i', '<img src="' . $attachmentContainer[$1]['attachment'] . '" width="' . $attachment[$1]['width'] . '" />', $getThread['message']);

我的问题: 在javascript或php中做得更好吗? 我怎么preg_replace所有[attach] [/ attach]与db的正确src和width存储? 并检查内容,我如何处理这些“空格”到换行?

我想拉出discuz! x3.0线程内容直接来自db。

感谢教学!

1 个答案:

答案 0 :(得分:0)

我不太明白你想要什么,但是从你最后一段代码中我会说你需要preg_replace_callback,因为$attachmentContainer[$1]['attachment']在调用preg_replace之前不应该评估

因此,您的最后一块代码应如下所示:

$threadContainer = preg_replace_callback(
    '/\[attach\](.*?)\[\/attach\]/i',
    function ($matches) {
        return '<img src="' . $attachmentContainer[$matches[1]]['attachment'] . '" width="' . $attachment[$matches[1]]['width'] . '" />';
    },
    $getThread['message']
);