2017-01-02 26 views
0

我有一個WordPress博客從Flickr拉取RSS提要。一個插件抓取XML中的<description>標籤並創建一個待處理的帖子。我有一個修改嵌入圖像的PHP函數,我試圖在同一個函數中刪除一些額外的文本。我使用的是str_replace和一串字符串(as suggested here)。在WordPress中診斷PHP函數的方法

我的問題是,我試圖替換的第一個字符串($att[0])不被我的函數取代。

rss.xml

<description> 
    <!-- This first string is always the same, I'd like to remove it --> 
    <p><a href="https://someUrlHere.com">username</a> posted a photo:</p> 
    <p><a href="https://linkToimage.com"><img src="https://imgSrc.jpg" /></a></p> 
</description> 

的functions.php

function edit_content($content) { 
    // Set the array of strings 
    // $att[0] is not replaced by the function. Why? 
    // $att[1] is replaced 
    $att = array('<p><a href=\"https://www.flickr.com/people/bennettscience/\">bennettscience</a> posted a photo: </p>', '_m.jpg'); 
    $replace = array(' ', '_b.jpg'); 

    // Modify the content and return to the post. 
    $content = str_replace($att, $replace, $content); 
    return $content; 
} 
add_filter('the_content', 'edit_content'); 

我想我有兩個問題:

  1. 有什麼明顯的我失蹤功能?
  2. 如何調試腳本?當我在WordPress中更新文件時,沒有給出PHP錯誤。在這一點上我不太熟悉PHP。

回答

1

您在XML文件和PHP字符串之間的空格有所不同。你需要100%確定字符串是,確切地說是一樣的。空白區別很重要。

您發佈的XML文件在photo:</p>中沒有空格,但您的PHP字符串有photo: </p>

比較:

// XML 
<p><a href="https://someUrlHere.com">username</a> posted a photo:</p> 
// PHP 
<p><a href=\"https://www.flickr.com/people/bennettscience/\">bennettscience</a> posted a photo: </p> 

另外,強制性記:你最好不要使用,而不是str_replace()preg_replace()一個實際的解析器。請參閱this classic post瞭解原因的解釋。

+0

認爲它是那樣的小東西。仍然沒有工作,但我剛剛發現我正在使用的插件添加了三個領先的選項卡,顯然不在搜索字符串中,我也可以切換到'preg_replace()'來處理前導空格比嘗試和確切代碼'str_replace()'。謝謝。 – Brian

+0

@BrianBennett是的,在這裏使用'str_replace()'會很棘手;如果Flickr曾經改變過任何關於他們的提要,它可能會破壞你的腳本。你最好使用實際的解析器,而不是'str_replace()'或'preg_replace()'。此外,僅供參考,我推薦使用一個好的IDE(如PHPStorm)和調試器來檢查將來的這些事情。 –