亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在特定元素之間插入 div

在特定元素之間插入 div

PHP
肥皂起泡泡 2023-11-03 16:50:26
我之前構建了一些 html 頁面,其中幾個段落位于 div 內,現在我想將其移動到 WordPress 中以了解主題和 CMS 的結構,但我有一些問題需要理解。例如,在循環中,我不能只在起點添加開始 div,在末尾添加結束 div(顯然),因為在中間有不同的元素包裹在其他 div 中。例如,我想采用最后一段,使用自定義類在其周圍創建一個包裝 div,我的解決方案是這樣的。我確信這是一個完全混亂的解決方案。我究竟做錯了什么?    // First function                       function addDivLastP1( $content ) {                                $pattern = '/[\s\S]*\K(<p>)/i';                 // Here i adding the opening tag div. I close it later in another function                $replacement = '<div class="my_class">$1';                                $content = preg_replace( $pattern, $replacement, $content );                return $content;                }                                add_filter( 'the_content', 'addDivLastP1' );                                                    // Second function                function addDivLastP2( $content ) {                                $pattern = '/[\s\S]*\K(<\/p>)/i';            // Closing div previously open                $replacement = '</div>';                                $content = preg_replace( $pattern, $replacement, $content );                return $content;                }                                add_filter( 'the_content', 'addDivLastP2' );
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

通過正則表達式解析 HTML(或任何 XML)并不是一個好主意。

在您的情況下,最好使用DOMDocument:

function addDivLastP( $content ) {


$doc = new DOMDocument();

if(!$doc->loadHTML($content)) {

? ? // cannot parse HTML content

? ? return $content;

}


for($i = $doc->childNodes->count()-1; $i >= 0; $i--) {

? ? $child = $doc->childNodes[$i];

? ? if ($child->nodeName === 'p') { // got last paragraph inside root node

? ? ? ? $div = $doc->createElement('div');

? ? ? ??

? ? ? ? // replace paragraph by new empty div

? ? ? ? $doc->replaceChild($div, $child);


? ? ? ? // insert paragraph inside div

? ? ? ? $div->appendChild($child);

? ? ? ? return $doc->saveHTML();

? ? }

}


return $content;


}



查看完整回答
反對 回復 2023-11-03
  • 1 回答
  • 0 關注
  • 169 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號