我試圖將[quote =「author」] text [/ quote]轉換爲格式化的div區塊。preg_match_all和preg_replace foreach循環
$p_text
:
[quote="person1"]Hello![/quote]
[quote="person2"]Hi![/quote]
功能:
function bbCode($p_text){
$pattern = '/\[quote="(.+?)"\]/'; // matches the author name, i.e. person1
preg_match_all($pattern, $p_text, $matches);
$authorCounter = 0;
foreach ($matches as $matchgroup) {
$author = $matchgroup[$authorCounter];
$pattern1 = '/\[quote=".+?"\]/'; // captures [quote="..."]
$replacement1 = '<div class="quote"><strong class="quote-author">' . $author . ' wrote:</strong><br>';
$p_text = preg_replace($pattern1, $replacement1, $p_text);
$authorCounter++;
}
$pattern2 = '/\[\/quote\]/'; // captures [/quote]
$replacement2 = '</div>';
$p_text = preg_replace($pattern2, $replacement2, $p_text);
return $p_text;
}
這與 「PERSON2」 更換兩個帖的作者,因爲第二foreach
迭代再次替換文本(?)。我怎樣才能確保每個報價都有正確的人名?
請試試我的庫解析簡碼和BBCodes:https://github.com/thunderer/Shortcode。如果您需要更多信息,請提交問題,我會提供幫助。 –