簡體   English   中英

如何使用PHP替換preg replace回調中的第一個和最后一個實例?

[英]How how do I replace the first and last instance in preg replace callback with PHP?

我正在用PHP和CodeIgniter創建一個自定義論壇。 我正在嘗試對bbCode解析器進行編碼,但是,我遇到了一個問題。 我使用preg_replace_callback替換了[quote id = 123] [/ quote]標簽。 如果只有一個級別的引號,它會很好地工作,但是一旦我嘗試“嵌套”引號標簽,一切都會被拋棄。 解析引號標簽后,應替換第一個打開的引號標簽和最后一個關閉的引號標簽。 而是,它僅解析第一個打開引號標簽和第一個關閉引號標簽。 誰能想到解決方法? 這是我的代碼:

$str = "[quote id=123][quote id=456]This is the second level[/quote]This is the first level[/quote]";

$str = preg_replace_callback("^\[quote id=([0-9]+)\](.*?)\[/quote\]^", "_parse_quote", $str);

return $str;

function _parse_quote($matches){

        $str = '';

        $CI =& get_instance();

        $query_message = "
                SELECT
                        message_id, author_id, date_posted
                FROM forum_messages
                WHERE message_id = ".$matches[1]."
                LIMIT 1";

        if($query_message = $CI->db->query($query_message)){

                if($query_message->num_rows() > 0){

                        $message = $query_message->row_array();

                        $CI->member->get_info($message['author_id']);
                        $author = $CI->member->info;

                        $str = '
                                <blockquote title="Originally posted by '.$author['display_name'].' about '.timespan(strtotime($message['date_posted']), time()).' ago...">
                                        <p>'.$matches[2].'</p>
                                </blockquote>
                                ';

                }

        }

        return $str;
}

如果運行正則表達式先找到所有引號,該怎么辦:

$str = "[quote id=123][quote id=456]This is the second level[/quote]This is the first level[/quote]";
$quotes = null;
preg_match_all('^\[quote id=([0-9]+)\]^', $str, $quotes);
var_dump($quotes);

利用此信息,您可以為從最內到外的每個報價動態生成特定的正則表達式替換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM