2017-06-07 43 views
0

所以我試圖在wordpress中通常更換公司名稱的每個實例,並且偶爾遇到問題(通常在鏈接的href中)它正在中斷鏈接。排除str_replace中的html屬性

代碼我使用(包括ACF自定義字段過濾器)

//Replace the word lunch with a span 
function replace_text_wps($text){ 
    $replace = array(
     // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS' 
     'lunch!' => '<span class="lunch">lunch!</span>', 
     'Lunch!' => '<span class="lunch">lunch!</span>', 
     'LUNCH!' => '<span class="lunch">lunch!</span>' 
    ); 
    $text = str_replace(array_keys($replace), $replace, $text); 
    return $text; 
} 

add_filter('the_content', 'replace_text_wps'); 
add_filter('the_excerpt', 'replace_text_wps'); 
add_filter('the_title', 'replace_text_wps'); 
add_filter('acf_the_content', 'replace_text_wps'); 

有沒有辦法只能替換它的類似HREF標記以外的東西?我已經研究過像DOM解析這樣的東西,但我不確定是否有一個更簡單的方法 - 它在任何其他情況下似乎都不會導致悲傷,所以我不確定那個pre =處理整個HMTL並尋找單詞是合適的。我確實想知道如何在字符串之前和之後搜索字符串,但是我不確定如何包含前導/尾隨空格,並且感覺有點不舒服? 在此先感謝! Pete

回答

1

ok,所以在這個例子中,這是非常具體的,我發現下面的代碼工作得很好。在最初的匹配參數中添加尾隨/前導空格,以及在包含空格的html標記之後直接找到它的變體。 不太優雅,但足以達到此目的。

function replace_text_wps($text){ 
    $replace = array(
     // used mid-line 
     ' lunch! ' => ' <span class="lunch">lunch!</span> ', 
     ' Lunch! ' => ' <span class="lunch">lunch!</span> ', 
     ' LUNCH! ' => ' <span class="lunch">lunch!</span> ', 
     // used at end of lines 
     ' lunch!' => ' <span class="lunch">lunch!</span>', 
     ' Lunch!' => ' <span class="lunch">lunch!</span>', 
     ' LUNCH!' => ' <span class="lunch">lunch!</span>', 
     // used inside html tags like headers 
     '>lunch!' => '><span class="lunch">lunch!</span>', 
     '>Lunch!' => '><span class="lunch">lunch!</span>', 
     '>LUNCH!' => '><span class="lunch">lunch!</span>', 
     //used directly after html tags 
     '> lunch!' => '> <span class="lunch">lunch!</span>', 
     '> Lunch!' => '> <span class="lunch">lunch!</span>', 
     '> LUNCH!' => '> <span class="lunch">lunch!</span>', 
     //exclude alt tags on images, title attributes etc 
     '"lunch!' => '"lunch!', 
     'lunch!"' => 'lunch!"', 
     '"Lunch!' => '"lunch!', 
     'Lunch!"' => 'lunch!"' 
    ); 
    $text = str_replace(array_keys($replace), $replace, $text); 
    return $text; 
} 
add_filter('the_content', 'replace_text_wps'); 
add_filter('the_excerpt', 'replace_text_wps'); 
add_filter('the_title', 'replace_text_wps'); 
add_filter('acf_the_content', 'replace_text_wps'); 
+0

等待期結束後,請務必接受您的回答,以便大家都知道問題已經解決。除非有人想出一個更好的解決方案,否則你當然想等待。 – Christoph