簡體   English   中英

字符串替換div的內容

[英]String replace the contents of a div

我想做的事:

我有一個具有ID的div。 每當出現“>”時,我都希望將其替換為“ >>”。 我還想在div前面加上“ You are here:”。

例:

<div id="bbp-breadcrumb">Home &gt; About &gt; Contact</div>

內容:

我的div包含bbPress的面包屑鏈接,但我正在嘗試將其格式與我用於WordPress的站點級面包屑插件相匹配。 div在PHP中稱為函數,並輸出為HTML。

我的問題:

我是否使用Javascript的PHP替換符號,以及如何首先調用div的內容?

查找生成&lt;的代碼&lt; ,然后設置適當的選項( breadcrumb_separator分隔符左右),或修改php代碼以更改分隔符。

使用JavaScript修改所謂的靜態文本不僅是維護的噩夢,而且非常脆弱,並且可能導致奇怪的呈現(因為如果系統運行緩慢,用戶會看到您的網站已被修改),但在沒有(或禁用)的瀏覽器中也無法使用)JavaScript支持。

您可以使用CSS添加“您在這里”文本:

#bbp-breadcrumb:before {
    content: "You are here: ";
}

瀏覽器支持:
http://www.quirksmode.org/css/beforeafter_content.html

您可以使用javascript將>更改為>>:

var htmlElement = document.getElementById('bbp-breadcrumb');
htmlElement.innerHTML = htmlElement.innerHTML.split('&gt;').join('&gt;&gt;').split('>').join('>>')

我不建議像這樣更改內容,這確實很麻煩。 如果可能的話,最好更改面包屑插件的輸出渲染。 在Wordpress中,這應該是可行的。

您可以使用正則表達式來匹配面包屑內容..對其進行更改..並將其放回上下文中..檢查這是否對您有幫助:

    $the_existing_html = 'somethis before<div id="bbp-breadcrumb">Home &gt; About &gt; Contact</div>something after'; // let's say this is your curreny html.. just added some context
    echo $the_existing_html, '<hr />'; // output.. so that you can see the difference at the end 
    $pattern ='|<div(.*)bbp-breadcrumb(.*)>(.*)<\/div>|sU'; // find some text that is in a div that has "bbp-breadcrumb" somewhere in its atributes list

    $all = preg_match_all($pattern, $the_existing_html, $matches); // match that pattern

    $current_bc = $matches[3][0]; // get the text inside that div

    $new_bc = 'You are here: ' . str_replace('&gt;', '&gt;&gt;', $current_bc);// replace entity for > with the same thing repeated twice 

    $the_final_html = str_replace($current_bc, $new_bc, $the_existing_html); // replace the initial breadcrumb with the new one 
    echo $the_final_html; // output to see where we got 

暫無
暫無

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

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